Java Reference
In-Depth Information
Class
SharedBufferTest
In class
SharedBufferTest
(Fig. 23.13), line 12 creates an
ExecutorService
to execute
the
Producer
and
Consumer
Runnable
s. Line 15 creates an
UnsynchronizedBuffer
and as-
signs it to
Buffer
variable
sharedLocation
. This object stores the data that the
Producer
and
Consumer
threads will share. Lines 24-25 create and execute the
Producer
and
Con-
sumer
. The
Producer
and
Consumer
constructors are each passed the same
Buffer
object
(
sharedLocation
), so each object refers to the same
Buffer
. These lines also implicitly
launch the threads and call each
Runnable
's
run
method. Finally, line 27 calls method
shutdown
so that the application can terminate when the threads executing the
Producer
and
Consumer
complete their tasks and line 28 waits for the scheduled tasks to complete.
When
main
terminates (line 29), the main thread of execution enters the
terminated
state.
1
// Fig. 23.13: SharedBufferTest.java
2
// Application with two threads manipulating an unsynchronized buffer.
3
import
java.util.concurrent.ExecutorService;
4
import
java.util.concurrent.Executors;
5
import
java.util.concurrent.TimeUnit;
6
7
public
class
SharedBufferTest
8
{
9
public
static
void
main(String[] args)
throws
InterruptedException
10
{
11
// create new thread pool with two threads
12
ExecutorService executorService = Executors.newCachedThreadPool();
13
14
// create UnsynchronizedBuffer to store ints
Buffer sharedLocation =
new
UnsynchronizedBuffer();
15
16
17
System.out.println(
18
"Action\t\tValue\tSum of Produced\tSum of Consumed"
);
19
System.out.printf(
20
"------\t\t-----\t---------------\t---------------%n%n"
);
21
22
// execute the Producer and Consumer, giving each
23
// access to the sharedLocation
24
executorService.execute(
new
Producer(sharedLocation));
executorService.execute(
new
Consumer(sharedLocation));
25
26
27
executorService.shutdown();
// terminate app when tasks complete
28
executorService.awaitTermination(
1
,
TimeUnit.MINUTES
);
29
}
30
}
// end class SharedBufferTest
Action Value Sum of Produced Sum of Consumed
------ ----- --------------- ---------------
Producer writes 1 1
1 is lost
2 is lost
Producer writes 2 3
Producer writes 3 6
Fig. 23.13
|
Application with two threads manipulating an unsynchronized buffer. (
Caution:
The example of Figs. 23.9-23.13 is
not
thread safe.) (Part 1 of 2.)