Also defined is the interface ScheduledExecutorService, which extends ExecutorService
to support the scheduling of threads.
The concurrent API defines two predefined executor classes: ThreadPoolExecutor
and ScheduledThreadPoolExecutor. ThreadPoolExecutor implements the Executor and
ExecutorService interfaces and provides support for a managed pool of threads.
ScheduledThreadPoolExecutor also implements the ScheduledExecutorService interface
to allow a pool of threads to be scheduled.
A thread pool provides a set of threads that is used to execute various tasks. Instead of
each task using its own thread, the threads in the pool are used. This reduces the overhead
associated with creating many separate threads. Although you can use ThreadPoolExecutor
and ScheduledThreadPoolExecutor directly, most often you will want to obtain an executor
by calling one of the following static factory methods defined by the Executors utility class.
Here are some examples:
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.
Each returns a reference to an ExecutorService that can be used to manage the pool.
A Simple Executor Example
Before going any further, a simple example that uses an executor will be of value. The
following program creates a fixed thread pool that contains two threads. It then uses that
pool to execute four tasks. Thus, four tasks share the two threads that are in the pool. After
the tasks finish, the pool is shut down and the program ends.
// A simple example that uses an Executor.
import java.util.concurrent.*;
class SimpExec {
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 {
cdl.await();
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home