java线程在结束后再次执行

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

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

public void disconnect() {
        client.setSendMessage(key + "disconnect");
        thd.setRunning(false);
        client.setRunning(false);
        try {
            client.getSock().close();
            inputDisabled = sendBtnDisabled = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

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

public void run() {
        while (running) {

            try {
                if (!sock.isClosed())
                    if ((receiveMessage = receiveRead.readLine()) != null) {
                        msg = receiveMessage;
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

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

8aqjt8rx

8aqjt8rx1#

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

while (running) {

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

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

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

相关问题