使用Executor界面时如何关闭套接字?

时间:2014-10-16 05:05:54

标签: java multithreading sockets

我正在尝试使用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));  
    }   

我的问题是当线程被停用并且已从线程池中删除时,我该如何关闭套接字?

1 个答案:

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