我正在尝试使用Executor接口在为TCP连接创建新线程时创建高效的线程池。这是我的代码:
ServerSocket server = new ServerSocket(20006);
Socket client = null;
Executor service = Executors.newCachedThreadPool();
boolean f = true;
while(f){
client = server.accept();
System.out.println("Connection established!");
service.execute(new ServerThread(client));
}
我的问题是当线程被停用并且已从线程池中删除时,我该如何关闭套接字?
答案 0 :(得分:0)
将套接字的引用传递给ServerThread
的构造函数,然后在run()
方法的最后一行,调用socket.close()
:
public class ServerThread implements Runnable // or extends Thread
{
private Socket socket;
public ServerThread(Socket socket)
{
this.socket = socket;
}
@Override
public void run()
{
// ...
socket.close();
}
}