2

I'm writing a client/server application in Java using sockets. In the server, I have a thread that accepts client connections, this thread runs indefinitely. At some point in my application, I want to stop accepting client connection, so I guess destroying that thread is the only way. Can anybody tell me how to destroy a thread?

Here's my code:

class ClientConnectionThread implements Runnable {

    @Override
    public void run() {
        try {
            // Set up a server to listen at port 2901
            server = new ServerSocket(2901);

            // Keep on running and accept client connections
            while(true) {
                // Wait for a client to connect
                Socket client = server.accept();
                addClient(client.getInetAddress().getHostName(), client);

                // Start a new client reader thread for that socket
                new Thread(new ClientReaderThread(client)).start();
            }
        } catch (IOException e) {
            showError("Could not set up server on port 2901. Application will terminate now.");
            System.exit(0);
        }
    }
}

As you can see, I have an infinite loop while(true) in there, so this thread will never stop unless somehow I stop it.

4

2 回答 2

3

The right way to do this would be to close the server socket. This will cause the accept() to throw an IOException which you can handle and quit the thread.

I'd add a public void stop() method and make the socket a field in the class.

private ServerSocket serverSocket;

public ClientConnectionThread() {
    this.serverSocket = new ServerSocket(2901);
}
...
public void stop() {
    serverSocket.close();
}
public void run() {
     while(true) {
         // this will throw when the socket is closed by the stop() method
         Socket client = server.accept();
         ...
     }
}
于 2013-02-19T00:08:33.443 回答
2

一般你不会。您要求它使用Thread.interrupt().

Javadoc中有一个很好的解释。

从链接:

停止的大多数用法应该由简单地修改一些变量以指示目标线程应该停止运行的代码替换。目标线程应该定期检查这个变量,如果变量指示它要停止运行,则以有序的方式从它的run方法返回。(这是 Java 教程一直推荐的方法。)为了确保停止请求的及时通信,变量必须是 volatile 的(或者对变量的访问必须是同步的)。

应该注意的是,在等待线程不响应的所有情况下Thread.interrupt,它也不会响应Thread.stop

对于您的具体情况,您将不得不致电serverSocket.close,因为它不会响应Thread.interrupt

于 2013-02-19T00:15:00.213 回答