Java Reference
In-Depth Information
blockingGet
methods. Again, we output messages from this class's
synchronized
methods
for demonstration purposes only—I/O
should not
be performed in
synchronized
blocks, be-
cause it's important to minimize the amount of time that an object is “locked.”
1
// Fig. 23.16: SynchronizedBuffer.java
2
// Synchronizing access to shared mutable data using Object
3
//
methods wait and notifyAll.
4
public class
SynchronizedBuffer
implements
Buffer
5
{
6
private
int
buffer =
-1
;
// shared by producer and consumer threads
7
private
boolean
occupied =
false
;
8
9
// place value into buffer
10
public
synchronized
void
blockingPut(
int
value)
throws
InterruptedException
11
12
{
13
// while there are no empty locations, place thread in waiting state
14
while
(occupied)
15
{
16
// output thread information and buffer information, then wait
17
System.out.println(
"Producer tries to write."
);
// for demo only
18
displayState(
"Buffer full. Producer waits."
);
// for demo only
19
wait();
20
}
21
22
buffer = value;
// set new buffer value
23
24
// indicate producer cannot store another value
// until consumer retrieves current buffer value
occupied =
true
;
25
26
27
28
displayState(
"Producer writes "
+ buffer);
// for demo only
29
30
notifyAll();
// tell waiting thread(s) to enter runnable state
31
}
// end method blockingPut; releases lock on SynchronizedBuffer
32
33
// return value from buffer
34
public
synchronized
int
blockingGet()
throws
InterruptedException
35
{
36
// while no data to read, place thread in waiting state
37
while
(!occupied)
38
{
39
// output thread information and buffer information, then wait
40
System.out.println(
"Consumer tries to read."
);
// for demo only
41
displayState(
"Buffer empty. Consumer waits."
);
// for demo only
42
wait();
43
}
44
45
// indicate that producer can store another value
// because consumer just retrieved buffer value
occupied =
false
;
46
47
Fig. 23.16
|
Synchronizing access to shared mutable data using
Object
methods
wait
and
notifyAll
. (Part 1 of 2.)