Java:用socket清理runnable对象

时间:2012-02-12 14:48:55

标签: java multithreading sockets

我正在用Java编写一个多线程服务器应用程序。 一切都很好,但有一个小问题。 当我停止侦听传入连接请求的runnable时,套接字保持存在。所以我的问题是:如何停止一个可运行的对象并清理在这个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") ; 

Runnable代码:

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() ; 
    } 
    }

谢谢,汤姆

2 个答案:

答案 0 :(得分:2)

您可以从主线程关闭套接字。这将打破对accept的调用,并使其抛出IOException。然后,您可以从run的捕获中退出接受线程的IOException方法。

答案 1 :(得分:1)

您需要通过调用套接字的close方法显式关闭ServerSocket。执行此操作的最佳位置是Worldwide - 类run - 方法,finally - 块(因此即使发生异常,套接字也会关闭)。