- Executor provides an alternative way of managing threads through the
Thread
class.
- The
ExecutorService
interface extends Executor
by adding methods that help manage and control the execution of threads.
ScheduledExecutorService
interface is also defined which extends ExecutorService
to support the scheduling of threads.
- Executors utility class provides the following static factory methods to obtain executors.
static ExecutorService newCachedThreadPool()
static ExecutorService newFixedThreadPool(int numThreads)
static ScheduledExecutorService newScheduledThreadPool(int numThreads)
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Task implements Runnable {
CountDownLatch latch;
String name;
Task(CountDownLatch latch, String name){
this.latch = latch;
this.name = name;
}
/**
* Runs this operation.
*/
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println(this.name + ": " + i);
this.latch.countDown();
}
}
}
public class Main {
public static void main(String[] args) {
CountDownLatch cdl1 = new CountDownLatch(5);
CountDownLatch cdl2 = new CountDownLatch(5);
CountDownLatch cdl3 = new CountDownLatch(5);
CountDownLatch cdl4 = new CountDownLatch(5);
CountDownLatch cdl5 = new CountDownLatch(5);
ExecutorService executor = Executors.newFixedThreadPool(2);
System.out.println("Starting...");
executor.execute(new Task(cdl1, "A"));
executor.execute(new Task(cdl2, "B"));
executor.execute(new Task(cdl3, "C"));
executor.execute(new Task(cdl4, "D"));
executor.execute(new Task(cdl5, "E"));
try{
cdl1.await();
cdl2.await();
cdl3.await();
cdl4.await();
cdl5.await();
}catch (InterruptedException ex){
System.out.println(ex.getCause());
}
executor.shutdown();
System.out.println("Done");
}
}