【发布时间】:2015-11-04 22:27:29
【问题描述】:
我在终止等待accept() 调用的线程时遇到问题。
accept():侦听与此套接字建立的连接并接受它。该方法会一直阻塞,直到建立连接。
我有实现Runnable 接口的GestorBuzon:
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() 并且线程不会终止。我做错了什么?
【问题讨论】:
-
你能中断你的线程以阻止它们在
accept()上等待吗? -
这个 Runnable 类是一个连接监听器,当我不想做更多 accept() (来自客户端的连接)时,我使用 contextDestroyed() 。我不知道其他形式可以正确终止它。
-
在
gestorBuzon.terminate()之后调用thread.interrupt()? -
@AndyTurner
java.net的方法不可中断。 -
Thread.destroy() 已弃用。
标签: java multithreading sockets