Java Thread How to - Use cached thread pool with ExecutorService








Question

We would like to know how to use cached thread pool with ExecutorService.

Answer

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//ww w.  ja  v  a2  s  . co  m
public class Main {
  int sum;
  public static void main(String[] args) {
    ExecutorService pool = Executors.newCachedThreadPool();
    Main app = new Main();
    for (int i = 0; i < 1000; i++) {
      pool.execute(app.new Adding());
    }
    pool.shutdown();
    while (!pool.isTerminated()) {
      System.out.println(" Is it done? : " + pool.isTerminated());
    }
    System.out.println(" Is it done? : " + pool.isTerminated());
    System.out.println("Sum is " + app.sum);
  }

  class Adding implements Runnable {
    public void run() {
      synchronized (Main.this) {
        sum += 1;
      }
    }
  }
}

The code above generates the following result.