我正在用 Java 编写一个多线程服务器应用程序。 一切工作正常,但有一个小问题。 当我停止监听传入连接请求的可运行程序时,套接字保持现有状态。所以我的问题是:如何停止可运行对象并清理此可运行对象中生成的所有对象?
停止线程的代码:
Runnable tr = new Worldwide() ;
Thread thread = new Thread(tr) ;
thread.start() ;
online = true ;
while (core.getServerSate()) {
try{
Thread.sleep(200);
} catch (Exception e ) {
e.printStackTrace();
}
} ;
thread.stop() ;
thread.
core.printToConsole("Server is offline now") ;
可运行代码:
public class Worldwide implements Runnable {
Core core = Core.getInstance() ;
public Worldwide () {
}
@Override
public void run() {
try {
ServerSocket server = new ServerSocket(port) ;
core.printToConsole("Server is online") ;
core.printToConsole ( "listening on port :" + server.getLocalPort()) ;
while (core.getServerSate() == true) {
Socket client = server.accept() ;
Runnable tr = new ClientCommunication(client) ;
new Thread (tr).start() ;
}
}
catch(Exception e ) {
core.printToConsole ("An error occured while going online") ;
e.printStackTrace() ;
}
}
谢谢,汤姆
最佳答案
您可以从主线程关闭套接字。这将中断对 accept
的调用并导致抛出 IOException
。然后,您可以从 IOException
的捕获中退出接受线程的 run
方法。
关于Java : clean up runnable object with socket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9249679/