Java Reference
In-Depth Information
A classic example of thread communication involving conditions is the relationship
between a producer thread and a consumer thread. The producer thread produces data
items to be consumed by the consumer thread. Each produced data item is stored in a
shared variable.
Imagine thatthethreadsarenotcommunicating andarerunningatdifferentspeeds.
Theproducermightproduceanewdataitemandrecorditinthesharedvariablebefore
theconsumerretrievesthepreviousdataitemforprocessing.Also,theconsumermight
retrieve the contents of the shared variable before a new data item is produced.
Toovercomethoseproblems,theproducerthreadmustwaituntilitisnotifiedthatthe
previouslyproduceddataitemhasbeenconsumed,andtheconsumerthreadmustwait
untilitisnotifiedthatanewdataitemhasbeenproduced. Listing4-27 showsyouhow
to accomplish this task via wait() and notify() .
Listing 4-27. The producer-consumer relationship
class PC
{
public static void main(String[] args)
{
Shared s = new Shared();
new Producer(s).start();
new Consumer(s).start();
}
}
class Shared
{
private char c = '\u0000';
private boolean writeable = true;
synchronized void setSharedChar(char c)
{
while (!writeable)
try
{
wait();
}
catch (InterruptedException e) {}
this.c = c;
Search WWH ::




Custom Search