Java Reference
In-Depth Information
22 synchronized (resourceThree) {
23 resourceThree.value = -1;
24 }
25 }
26
27 private static class Resource {
28 int value;
29 }
30 }
The notify and notifyAll Methods
Every Java object has the capability to broadcast a call, notifying threads that have called the
wait
method on that object that some event that they might be interested in has occurred. If
you call the
notify
method, one of the threads waiting on that object is told to come out of the
waiting state and block until it can regain the lock on the object, after which it can continue
processing. If you call
notifyAll
, every thread waiting for the object is told to come out of the
waiting state and block until it can regain the lock on the object, after which it can continue
processing.
■
Caution
It is easy to become confused when talking about threads waiting.
Thread.State.WAITING
has a specific meaning in Java, namely that the thread has called the
wait
or the
join
methods. When a
thread enters the
Thread.State.WAITING
state by calling the
wait
method, it consumes no CPU cycles
until some other thread calls either
notify
or
notifyAll
on the same object that
wait
was called on,
or until the thread is interrupted. When a thread enters the
Thread.State.WAITING
state by calling the
join
method, it consumes no CPU cycles until the thread it is trying to join terminates, or until the thread is
interrupted. In contrast, if several threads attempt to obtain the same lock simultaneously, one will obtain it,
and the remainder will enter the
Thread.State.Blocked
state until the lock is released, at which time
another thread will obtain the lock—the JVM scheduler handles automatically selecting another thread from
those in the
Thread.State.Blocked
state.
Listing 4-5 demonstrates the difference between calling
notify
and
notifyAll
.
Listing 4-5.
NotifyVersusNotifyAll.java
1 public class NotifyVersusNotifyAll extends Thread {
2 private static Object mutex = new Object();
3
4 public static void main(String[] args) throws InterruptedException {
5 for (int i = 0; i < 5; i++) {
6 new NotifyVersusNotifyAll().start();
7 }
8
9 Thread.sleep(2000);