Java Reference
In-Depth Information
}
class Consumer extends Thread
{
private Shared s;
Consumer(Shared s)
{
this.s = s;
}
@Override
public void run()
{
char ch;
do
{
synchronized(s)
{
ch = s.getSharedChar();
System.out.println(ch+"
consumed
by
con-
sumer.");
}
}
while (ch != 'Z');
}
}
Theapplicationcreatesa
Shared
objectandtwothreadsthatgetacopyoftheob-
ject's reference. The producer calls the object's
setSharedChar()
method to save
each of 26 uppercase letters; the consumer calls the object's
getSharedChar()
method to acquire each letter.
The
writeable
instance field tracks two conditions: the producer waiting on the
consumertoconsumeadataitem,andtheconsumerwaitingontheproducertoproduce
a new data item. It helps coordinate execution of the producer and consumer. The fol-
lowing scenario, where the consumer executes first, illustrates this coordination:
1. The consumer executes
s.getSharedChar()
to retrieve a letter.