这涉及通过套接字的服务器-客户端网络。客户端线程在 while(boolean)
循环上运行。它是从 ClientBean 类访问的,并且条件设置为 false。这应该停止线程或终止它。但在我将线程的运行循环条件设置为 false 后,我看到线程尝试再次读取套接字的 InputStream。这会抛出SocketException。
bean 的代码部分:-
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() 循环会再次执行?此外,当我从 bean 关闭套接字时,它如何满足条件 if (!sock.isClosed())
?
最佳答案
Why does the loop of run() execute once more after thread is stopped?
你的循环状态
while (running) {
所以它会循环直到running = false
注意,当你这样做时
} catch (IOException e) {
e.printStackTrace(); // print error and pretend it didn't happen.
}
简单的解决方案是将 try/catch 放在循环之外,以便当发生错误时它会中断循环,或者您可以关闭连接并重试
how does it satisfy the condition if (!sock.isClosed()) when I have closed the socket from bean?
一旦您在套接字上调用 close(),此方法将返回 isClosed == true。
关于java - 线程结束后再次执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36262194/