Java Reference
In-Depth Information
52
53
// return value from buffer
54
public int
blockingGet()
throws
InterruptedException
55
{
56
int
readValue =
0
;
// initialize value read from buffer
57
accessLock.lock();
// lock this object
58
59
// output thread information and buffer information, then wait
60
try
61
{
62
// if there is no data to read, place thread in waiting state
63
while
(!occupied)
64
{
65
System.out.println(
"Consumer tries to read."
);
66
displayState(
"Buffer empty. Consumer waits."
);
67
canRead.await();
// wait until buffer is full
68
}
69
70
// indicate that producer can store another value
71
// because consumer just retrieved buffer value
72
occupied =
false
;
73
74
readValue = buffer;
// retrieve value from buffer
75
displayState(
"Consumer reads "
+ readValue);
76
77
// signal any threads waiting for buffer to be empty
canWrite.signalAll();
78
79
}
80
finally
81
{
82
accessLock.unlock();
// unlock this object
83
}
84
85
return
readValue;
86
}
87
88
// display current operation and buffer state
89
private
void
displayState(String operation)
90
{
91
try
92
{
93
94
System.out.printf(
"%-40s%d\t\t%b%n%n"
, operation, buffer,
95
occupied);
96
}
97
finally
98
{
99
100
}
101
}
102
}
// end class SynchronizedBuffer
accessLock.lock();
// lock this object
accessLock.unlock();
// unlock this objects
Fig. 23.20
|
Synchronizing access to a shared integer using the
Lock
and
Condition
interfaces. (Part 2 of 2.)