gpt4 book ai didi

java - 如何销毁Java中的线程

转载 作者:行者123 更新时间:2023-11-30 06:25:59 25 4
gpt4 key购买 nike

我正在使用套接字用 Java 编写客户端/服务器应用程序。在服务器中,我有一个接受客户端连接的线程,这个线程无限期地运行。在我的应用程序中的某个时刻,我想停止接受客户端连接,所以我想销毁该线程是唯一的方法。谁能告诉我如何销毁线程?

这是我的代码:

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

如您所见,我有一个无限循环 while(true) ,所以这个线程永远不会停止,除非我以某种方式停止它。

最佳答案

正确的做法是关闭服务器套接字。这将导致 accept() 抛出一个 IOException,您可以处理并退出线程。

我将添加一个 public void stop() 方法并使套接字成为类中的一个字段。

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

关于java - 如何销毁Java中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14947612/

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