嘿,所以我为 ExecutorService 的 java 文档选择了这个示例。我想确认这段代码的流程,Executors.newFixedThreadPool 将创建一个线程池(我猜)。所以 serversocket 将等待一个连接,一旦它获得一个连接,它就会启动一个线程,所以现在 poolsize 减 1。一旦线程完成执行,poolsize 将再次增加 1,不是吗?线程会放弃它使用的资源吗?
class NetworkService implements Runnable {
private final ServerSocket serverSocket;
private final ExecutorService pool;
public NetworkService(int port, int poolSize)
throws IOException {
serverSocket = new ServerSocket(port);
pool = Executors.newFixedThreadPool(poolSize);
}
public void run() { // run the service
try {
for (;;) {
pool.execute(new Handler(serverSocket.accept()));
}
} catch (IOException ex) {
pool.shutdown();
}
}
}
class Handler implements Runnable {
private final Socket socket;
Handler(Socket socket) { this.socket = socket; }
public void run() {
// read and service request on socket
}
}