Java Reference
In-Depth Information
the two threads share the same object. The
Consumer
thread in this program performs the
tasks specified in method
run
(lines 17-39). Lines 21-34 iterate 10 times. Each iteration
invokes
Thread
method
sleep
(line 26) to put the
Consumer
thread into the
timed waiting
state for up to 3 seconds. Next, line 27 uses the
Buffer
's
blockingGet
method to retrieve
the value in the shared buffer, then adds the value to variable
sum
. Line 28 displays the
total of all the values consumed so far. When the loop completes, lines 36-37 display a
line indicating the sum of the consumed values. Then method
run
terminates, which in-
dicates that the
Consumer
completed its task. Once both threads enter the
terminated
state,
the program ends.
1
// Fig. 23.11: Consumer.java
2
// Consumer with a run method that loops, reading 10 values from buffer.
3
import
java.security.SecureRandom;
4
5
6
public class
Consumer
implements
Runnable
{
7
private static
final
SecureRandom generator =
new
SecureRandom();
8
private final
Buffer sharedLocation;
// reference to shared object
9
10
// constructor
11
public
Consumer(Buffer sharedLocation)
12
{
13
this
.sharedLocation = sharedLocation;
14
}
15
16
// read sharedLocation's value 10 times and sum the values
public void
run()
17
18
{
19
int
sum =
0
;
20
21
for
(
int
count =
1
; count <=
10
; count++)
22
{
23
// sleep 0 to 3 seconds, read value from buffer and add to sum
24
try
25
{
26
Thread.sleep(generator.nextInt(
3000
));
sum += sharedLocation.blockingGet();
27
28
System.out.printf(
"\t\t\t%2d%n"
, sum);
29
}
30
catch
(InterruptedException exception)
31
{
32
Thread.currentThread().interrupt();
33
}
34
}
35
36
System.out.printf(
"%n%s %d%n%s%n"
,
37
"Consumer read values totaling"
, sum,
"Terminating Consumer"
);
38
}
39
}
// end class Consumer
Fig. 23.11
|
Consumer
with a
run
method that loops, reading 10 values from buffer. (
Caution:
The example of Figs. 23.9-23.13 is
not
thread safe.)