---
title: "java 线程池 用法"
author: "xxtianxiaxing"
date: "2009-08-07T12:26:23Z"
tags: []
categories: ["非技术"]
slug: "java"
draft: false
lastmod: "2009-08-07T12:26:23Z"
id: 442229
url: "https://xylonwang.iteye.com/blog/442229"
---

```java

    
class NetworkService {
    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 serve() {
      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
    }
 }


```