我在终止等待 accept()
调用的线程时遇到问题。
accept()
:监听与此套接字建立的连接并接受它。该方法会阻塞,直到建立连接为止。
我有GestorBuzon
,它实现了Runnable
接口(interface):
public class GestorBuzon implements Runnable{
private static volatile boolean running = true;
public void run() {
try {
while (running) {
-- pre code
accept();
-- post code
}
} catch(IOException e) {
terminate();
}
}
public static void terminate() {
running = false;
}
}
我有 MessageSystem
类来启动和停止线程:
public class MessageSystem {
private GestorBuzon gestorBuzon;
private Thread thread;
public MessageSystem() {
// Starts the Thread
contextInitialized();
}
private void contextInitialized() {
gestorBuzon = new GestorBuzon();
thread = new Thread(gestorBuzon);
thread.start();
}
private void contextDestroyed() {
if (thread != null) {
gestorBuzon.terminate();
try {
thread.join();
} catch (InterruptedException e) {
gestorBuzon.terminate();
}
}
}
}
我多次调用Runnable
类中的accept()
函数,但是当我使用contextDestroyed()
函数时,线程仍然是等待 accept()
并且线程不会终止。我做错了什么?
最佳答案
只需通过 setSoTimeout()
在 ServerSocket
上设置套接字超时,并在触发时捕获 SocketTimeoutException
。然后,您可以检查 catch
block 等中的 running
标志,并决定是继续还是停止接受。
关于java - 停止长时间等待的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533284/