Java Reference
In-Depth Information
Waiting for a Notify
When a thread invokes wait() on an object, the following sequence of events occurs before
the thread runs again. Suppose that there are two threads, A and B:
1. Thread A invokes wait() on an object and gives up the lock on the object. Thread A
is now blocked.
2. Thread B grabs the lock and invokes notify() on the object.
3. Thread A wakes up, but the lock is not available because Thread B has it. There-
fore, Thread A is now waiting for the lock. In other words, Thread A just went from
one blocked state to another. Before, Thread A was waiting for a notify(). Now, it is
waiting for a lock to become available.
4. Thread B releases the lock (hopefully), and Thread A becomes runnable.
5. Before running again, Thread A must obtain the lock on the object.
Because multiple threads may be waiting and awoken at the same time, it is important
for a waiting thread to make sure that they should have been woken up. The PizzaChef
does this using a while loop:
synchronized(buffet)
{
while(!buffet.isEmpty())
{
try
{
System.out.println(“Chef is waiting...”);
buffet.wait();
}catch(InterruptedException e)
{}
}
}
When the PizzaChef thread receives a notify, it checks to make sure that the buffet is
actually empty. Why bother if it just received a notify? Well, suppose that by the time this
thread has a chance to run again, a second PizzaChef thread has already filled the buffet
with pizzas. If our first thread did not check that the buffet was empty, it would have filled
the buffet as well, causing overproduction, which is what we are trying to avoid in the first
place.
Placing a call to wait() in a while loop is a standard design when working with producer
and consumer threads.
Search WWH ::




Custom Search