gpt4 book ai didi

Java : clean up runnable object with socket

转载 作者:行者123 更新时间:2023-12-03 11:52:21 25 4
gpt4 key购买 nike

我正在用 Java 编写一个多线程服务器应用程序。
一切正常,但有一个小问题。
当我停止监听传入连接请求的 runnable 时,套接字保持存在。所以我的问题是:如何停止可运行对象并清除在该可运行对象中创建的所有对象?

停止线程的代码:

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 .然后您可以退出接受线程的 run方法来自 IOException .

关于Java : clean up runnable object with socket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9249679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com