Java Thread How to - Create new fixed thread pool threads








Question

We would like to know how to create new fixed thread pool threads.

Answer

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
//from ww w. j ava2s  .  c o  m
public class Main implements Runnable {

  public static void main(String[] args) throws InterruptedException {
    Main task = new Main();
    int threads = Runtime.getRuntime().availableProcessors();
    ExecutorService pool = Executors.newFixedThreadPool(threads);
    for (int i = 0; i < threads; i++) {
      pool.submit(task);
    }
    pool.awaitTermination(120, TimeUnit.SECONDS);
  }

  public void run() {
    System.out.println("Task running...");
    int i = 0;
    while (true) {
      i++;
    }
  }
}

The code above generates the following result.