Java Thread How to - Get threads not run in parallel using ExecutorService








Question

We would like to know how to get threads not run in parallel using ExecutorService.

Answer

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*  w w  w  . j a va  2s  . co m*/
public class Main {
  ExecutorService executor = Executors.newFixedThreadPool(50);
  public void startTenThreads() {
    for (int i = 0; i < 10; i++) {
      executor.execute(new FooWorker(i));
    }
  }
  public static void main(String[] args) {
    new Main().startTenThreads();
  }
}
class FooWorker implements Runnable {
  int threadNum;
  public FooWorker(int threadNum) {
    this.threadNum = threadNum;
  }
  public void run() {
    try {
      System.out.println("Thread " + threadNum + " starting");
      Thread.sleep(60000);
      System.out.println("Thread " + threadNum + " finished");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

The code above generates the following result.