JDK 中ExecutorService建立線程池

下面給出了一個網絡服務的簡單結構,這裏線程池中的線程做爲傳入的請求。它使用了預先配置的 Executors.newFixedThreadPool(int) 工廠方法:
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
    }
 }
下列方法分兩個階段關閉ExecutorService。第一階段調用shutdown拒絕傳入任務,而後調用shutdownNow(若有必要)取消全部遺留的任務:
void shutdownAndAwaitTermination(ExecutorService pool) {
   pool.shutdown(); // Disable new tasks from being submitted
   try {
     // Wait a while for existing tasks to terminate
     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
       pool.shutdownNow(); // Cancel currently executing tasks
       // Wait a while for tasks to respond to being cancelled
       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
           System.err.println("Pool did not terminate");
     }
   } catch (InterruptedException ie) {
     // (Re-)Cancel if current thread also interrupted
     pool.shutdownNow();
     // Preserve interrupt status
     Thread.currentThread().interrupt();
   }
 }

內存一致性效果:線程中向ExecutorService提交Runnable或Callable任務以前的操做 happen-before 由該任務所提取的全部操做,後者依次 happen-before 經過Future.get()獲取的結果。  網絡

相關文章
相關標籤/搜索