Java Reference
In-Depth Information
The first step is to fill the Queue with the tasks that need to be executed in parallel.
This is done by calling the Queue 's add() method and passing to it a class that im-
plements the Runnable interface. Once that's done, the executor is initialized.
The ThreadPoolExecutor constructor has many parameter options; the one
used in the solution is the simplest. Table 10-1 has a description of each parameter.
Table 10-1 . ThreadPoolExecutor's Parameters
Parameter
Description
The minimum number of threads that are created as tasks are submit-
ted
CorePoolSize
The maximum number of threads that the Executor would create
MaximumPoolSize
KeepAliveTime
The time that the waiting threads will wait for work before being dis-
posed (as long as the number of live threads is still more than the
CorePoolSize )
The unit on which the KeepAliveTime is expressed (that is,
TimeUnit.SECONDS, TimeUnit.MILLISECONDS )
TimeUnit
The Blocking queue that contains the tasks to be processed by the
Executor
WorkQueue
After the ThreadPoolExecutor is initialized, you call the pre-
startAllCoreThreads() . This method “warms up” the ThreadPoolEx-
ecutor by creating the number of threads specified in the CorePoolSize and act-
ively starts consuming tasks from the Queue if it is not empty.
Call the shutdown() method of the ThreadPoolExecutor to wait for all the
tasks to be completed. By calling this method, the ThreadPoolExecutor is in-
structed to accept no new events from the queue (previously submitted events will fin-
ish processing). This is the first step in the orderly termination of a ThreadPoolEx-
ecutor . Call the awaitTermination() method to wait for all the tasks in the
ThreadPoolExecutor to be done. This method will force the main thread to wait
until all the Runnable s in the ThreadPoolExecutor's queue have completed
executing. After all the Runnable s have executed, the main thread will wake up and
continue.
Note A ThreadPoolExecutor needs to be configured correctly to maximize
CPU usage. The most efficient number of threads for an executor depends on the types
 
 
Search WWH ::




Custom Search