An executor is a thread management module (thread creation and management).
java.util.concurrent provides two executor interfaces:
Executor is a simple standardized interface for defining custom thread-like subsystems, including:
- thread pools,
- asynchronous I/O,
- and lightweight task frameworks.
Depending on which concrete Executor class is being used, tasks may:
- execute in:
- a newly created thread,
- an existing task-execution thread,
- or the thread calling execute,
- and may execute
- or concurrently.
An object that executes submitted Runnable tasks.
An Executor is normally used instead of explicitly creating threads.
Executor executor = anExecutor; executor.execute(new RunnableTask1()); executor.execute(new RunnableTask2());
ExecutorService is more extensive interface Executor by providing a more complete asynchronous task execution framework.
An ExecutorService manages:
- scheduling of tasks,
- and controlled shutdown.
ExecutorServices provide methods arranging asynchronous execution of any function expressed as Callable, the result-bearing analog of Runnable.
The ScheduledExecutorService subinterface and associated interfaces add support for:
- and periodic
In a producer-consumer context:
// Start the threads ExecutorService targetWorkExecutor = Executors.newFixedThreadPool(targetWorkerCount); targetWorkExecutor.execute(resultSetLoaderConsumer); // Wait the producer producer.join(); producerWorkIsDone.set(true); // Shut down the targetWorkExecutor targetWorkExecutor.shutdown(); // And wait the termination of the threads targetWorkExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MICROSECONDS);