Java Reference
In-Depth Information
startAllCoreThreads() method, and then you wait until all the Runnable ob-
jects are done executing by calling the shutdown() method, followed by the
awaitTermination() method:
private void start() throws InterruptedException {
BlockingQueue<Runnable> queue = new
LinkedBlockingQueue<>();
for (int i =0;i < 10;i++) {
final int localI = i;
queue.add((Runnable) () -> {
doExpensiveOperation(localI);
});
}
ThreadPoolExecutor executor = new
ThreadPoolExecutor(10,10,1000,
TimeUnit.MILLISECONDS, queue);
executor.prestartAllCoreThreads();
executor.shutdown();
executor.awaitTermination(100000,TimeUnit.SECONDS);
System.out.println("Look ma! all operations were
completed");
}
How It Works
A ThreadPoolExecutor consists of two components: the Queue of tasks to be
executed, and the Executor , which tells how to execute the tasks. The Queue is
filled with Runnable objects, on which the method run() contains the code to be
executed.
The Queue used by a ThreadPoolExecutor is an implementer of the
BlockingQueue interface. The BlockingQueue interface denotes a queue in
which the consumers of the queue will wait (be suspended) if there are no elements
within the Queue . This is necessary for the ThreadPoolExecutor to work effi-
ciently.
Search WWH ::




Custom Search