java线程在结束后再次执行

w8biq8rn  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(400)

这涉及到通过套接字进行服务器-客户机联网。客户端线程正在上运行 while(boolean) 循环。它是从clientbean类访问的,条件设置为false。这应该停止线程或终止它。但是在我将线程的run循环的条件设置为false之后,我看到线程再次尝试读取socket的inputstream。这会引发socketexception。
豆子的密码part:-

  1. public void disconnect() {
  2. client.setSendMessage(key + "disconnect");
  3. thd.setRunning(false);
  4. client.setRunning(false);
  5. try {
  6. client.getSock().close();
  7. inputDisabled = sendBtnDisabled = true;
  8. } catch (IOException e) {
  9. // TODO Auto-generated catch block
  10. e.printStackTrace();
  11. }
  12. }

以及线程的run()方法:-

  1. public void run() {
  2. while (running) {
  3. try {
  4. if (!sock.isClosed())
  5. if ((receiveMessage = receiveRead.readLine()) != null) {
  6. msg = receiveMessage;
  7. }
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. try {
  12. Thread.sleep(1000);
  13. } catch (InterruptedException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }

我在电话里有个例外 if ((receiveMessage = receiveRead.readLine()) != null) . 为什么run()的循环会在线程停止后再次执行?而且它是如何满足条件的呢 if (!sock.isClosed()) 我什么时候把豆子的插座关上?

8aqjt8rx

8aqjt8rx1#

为什么run()的循环会在线程停止后再次执行?
你的循环状态

  1. while (running) {

所以它循环直到 running = false 注意,当你这样做

  1. } catch (IOException e) {
  2. e.printStackTrace(); // print error and pretend it didn't happen.
  3. }

简单的解决方案是将try/catch放在循环之外,这样当发生错误时它就会中断循环,或者您可以关闭连接并重试
如果(!当我从bean关闭套接字时?
在套接字上调用close()后,此方法将返回isclosed==true。

相关问题