Java Thread How to - Execute threads using ExecutorService








Question

We would like to know how to execute threads using ExecutorService.

Answer

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//from  w ww.j  av a2 s .  co m
public class Main {
  ExecutorService threads;
  public Main(int poolSize) {
    threads = Executors.newFixedThreadPool(poolSize);
  }
  public void createThread(String name) {
    threads.execute(new MyThread(name)); // Create MyThread
  }
  public static void main(String[] args) {
    Thread t = Thread.currentThread();
    Main t1 = new Main(3);
    t1.createThread("Child 1");
    t1.createThread("Child 2");
    for (int i = 0; i <= 5; i++) {
      try {
        Thread.sleep(1000);
      } catch (Exception e) {
        e.printStackTrace();
      }
      System.out.println("The cirrent Thread is " + t.getName()
          + " and thread ID is " + t.getId());
    }
  }
}
class MyThread extends Thread {
  public MyThread(String name) {
    super(name);
  }
  @Override
  public void run() {
    for (int i = 0; i <= 5; i++) {
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("The current Thread is " + super.getName()
          + " and thread ID is " + super.getId());
    }
  }
}

The code above generates the following result.