Java Reference
In-Depth Information
public final void notifyAll(). Similar to notify(), except that all waiting
threads are awoken instead of just one.
An object's lock is often referred to as its monitor . The term monitor
refers to that portion of the object responsible for monitoring the
behavior of the wait() and notify() methods of the object. To invoke any of
the wait() or notify() methods, the current thread must own the monitor
(lock) of the Object, meaning that calls to wait() and notify() always
appear in a critical section, synchronized on the Object.
The following example demonstrates a producer/consumer model that
uses wait() and notify(). The producer is a pizza chef, and the consumer is a
lunch crowd at a buffet. The following Buffet class represents the object that
will be used as the monitor:
public class Buffet
{
boolean empty;
public synchronized boolean isEmpty()
{
return empty;
}
public synchronized void setEmpty(boolean b)
{
empty = b;
}
}
The following PizzaChef class is a thread that contains a reference to a Buf-
fet object. If the buffet is not empty, the chef waits for a notify() to occur on the
Buffet object. If the buffet is empty, the chef cooks pizza for a random amount
of time. If the cooking time is long enough, the buffet is no longer empty and
the thread invokes notify() on the Buffet object.
public class PizzaChef extends Thread
{
private Buffet buffet;
public PizzaChef(Buffet b)
{
buffet = b;
}
public void run()
{
Search WWH ::




Custom Search