Java Reference
In-Depth Information
4
public static void main(String[] args) {
5
// Create a fixed thread pool with maximum three threads
6
ExecutorService executor = Executors.newFixedThreadPool( 3 );
create executor
7
8 // Submit runnable tasks to the executor
9 executor.execute( new PrintChar( 'a' , 100 ));
10 executor.execute( new PrintChar( 'b' , 100 ));
11 executor.execute( new PrintNum( 100 ));
12
13
submit task
// Shut down the executor
14
executor.shutdown();
shut down executor
15 }
16 }
Line 6 creates a thread pool executor with a total of three threads maximum. Classes PrintChar
and PrintNum are defined in Listing 30.1. Line 9 creates a task, new PrintChar('a',
100) , and adds it to the pool. Similarly, another two runnable tasks are created and added
to the same pool in lines 10 and 11. The executor creates three threads to execute three tasks
concurrently.
Suppose that you replace line 6 with
ExecutorService executor = Executors.newFixedThreadPool( 1 );
What will happen? The three runnable tasks will be executed sequentially because there is
only one thread in the pool.
Suppose you replace line 6 with
ExecutorService executor = Executors.newCachedThreadPool();
What will happen? New threads will be created for each waiting task, so all the tasks will be
executed concurrently.
The shutdown() method in line 14 tells the executor to shut down. No new tasks can be
accepted, but any existing tasks will continue to finish.
Tip
If you need to create a thread for just one task, use the Thread class. If you need to
create threads for multiple tasks, it is better to use a thread pool.
30.14
What are the benefits of using a thread pool?
Check
30.15
How do you create a thread pool with three fixed threads? How do you submit a task
to a thread pool? How do you know that all the tasks are finished?
Point
30.7 Thread Synchronization
Thread synchronization is to coordinate the execution of the dependent threads.
Key
Point
A shared resource may become corrupted if it is accessed simultaneously by multiple threads.
The following example demonstrates the problem.
Suppose you create and launch 100 threads, each of which adds a penny to an account.
Define a class named Account to model the account, a class named AddAPennyTask to add
a penny to the account, and a main class that creates and launches threads. The relationships
of these classes are shown in Figure 30.9. The program is given in Listing 30.4.
 
 
 
Search WWH ::




Custom Search