Java Executor interface

Introduction

The concurrent API Executor can control the execution of threads.

An executor offers an alternative to managing threads through the Thread class.

Executor interface defines the following method:

void execute(Runnable  thread) 

To get an executor, use one of the following static factory methods defined by the Executors utility class.

static ExecutorService newCachedThreadPool()  
static ExecutorService newFixedThreadPool(int numThreads)  
static ScheduledExecutorService newScheduledThreadPool(int numThreads) 

newCachedThreadPool() creates a thread pool that adds threads as needed but reuses threads if possible.

newFixedThreadPool() creates a thread pool that consists of a specified number of threads.

newScheduledThreadPool() creates a thread pool that supports thread scheduling.

following program creates a fixed thread pool that contains two threads.

 
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; 
 
public class Main { 
  public static void main(String args[]) { 
    CountDownLatch cdl = new CountDownLatch(5); 
    CountDownLatch cdl2 = new CountDownLatch(5); 
    CountDownLatch cdl3 = new CountDownLatch(5); 
    CountDownLatch cdl4 = new CountDownLatch(5); 
    ExecutorService es = Executors.newFixedThreadPool(2); 
 
    System.out.println("Starting"); 
 
    // Start the threads. 
    es.execute(new MyThread(cdl, "A")); 
    es.execute(new MyThread(cdl2, "B")); 
    es.execute(new MyThread(cdl3, "C")); 
    es.execute(new MyThread(cdl4, "D")); 
 
    try { /*w  ww . ja  v a2  s  . com*/
      cdl.await(); 
      cdl2.await(); 
      cdl3.await(); 
      cdl4.await(); 
    } catch (InterruptedException exc) { 
      System.out.println(exc); 
    } 
 
    es.shutdown(); 
    System.out.println("Done"); 
  } 
} 
 
class MyThread implements Runnable { 
  String name; 
  CountDownLatch latch; 
 
  MyThread(CountDownLatch c, String n) { 
    latch = c; 
    name = n; 
 
    new Thread(this); 
  } 
 
  public void run() { 
     
    for(int i = 0; i < 5; i++) { 
      System.out.println(name + ": " + i); 
      latch.countDown(); 
    } 
  } 
}



PreviousNext

Related