| The notifyAll() and wait() methods can be invoked only
by the thread that holds the lock. |
| |
| |
| The notifyAll() method |
| The notifyAll() method notifies all the threads waiting on the monitor
held by the current thread and wakes them up. |
| Example: |
public synchronized int get()
{
while (available == false)
{
try
{
wait();
}
catch (InterruptedException e)
{
}
}
available = false;
notifyAll();
// notifies Producer
return contents;
} |
| |
| In the above example the Producer/Consumer example, the
Consumer thread calls the get() method, so the Consumer
thread holds the monitor during the execution of get().
At the end of the get() method, the call to notifyAll() wakes
up the Producer thread that is waiting to get the monitor.
Now, the Producer thread can get the monitor and proceed. |
| |
| If multiple threads are waiting for a monitor, the
Java runtime system chooses one of the waiting threads
to run, making no commitments or guarantees about which thread will be chosen. |
| |
| |
| The wait() method |
| The wait() method causes the current thread
to wait (possibly forever) until another thread notifies it of a condition change. |
| We use wait() in conjunction
with notify() or notifyAll() to coordinate the
activities of multiple threads using the same resources. |
| |
| Example: |
public synchronized int get()
{
while (available == false)
{
try
{
wait();
// waits for notifyAll() call from Producer
} catch (InterruptedException e)
{
}
}
available = false;
notifyAll();
return contents;
} |
| |
| The Object class contains two other versions of the wait() method: |
| wait(long timeout) |
| |
| waits for notification or until the timeout period has
elapsed--timeout is measured in milliseconds. |
| wait(long timeout, int nanos) |
| |
| waits for notification or until timeout milliseconds plus
nanos nanoseconds have elapsed. |
| |
| It has a number of methods, some of which are static. |