Java Reference
In-Depth Information
14.4.
wait
,
notifyAll
, and
notify
The
synchronized
locking mechanism suffices for keeping threads from
interfering with each other, but you also need a way to communicate
between threads. For this purpose, the
wait
method lets one thread wait
until some condition occurs, and the notification methods
notifyAll
and
notify
tell waiting threads that something has occurred that might satis-
fy that condition. The
wait
and notification methods are defined in class
Object
and are inherited by all classes. They apply to particular objects,
just as locks do.
There is a standard pattern that is important to use with
wait
and notific-
ation. The thread waiting for a condition should always do something like
this:
synchronized void doWhenCondition() {
while (!
condition
)
wait();
… Do what must be done when the condition is true …
}
A number of things are going on here:
•
Everything is executed within synchronized code. If it were not,
the state of the object would not be stable. For example, if the
method were not declared
synchronized
, then after the
while
state-
ment, there would be no guarantee that the condition remained
TRue
: Another thread might have changed the situation that the
condition tests.
•
One of the important aspects of the definition of
wait
is that when
it pauses the thread, it
atomically
releases the lock on the ob-
ject. Saying that the thread suspension and lock release are atom-
ic means that they happen together, indivisibly. Otherwise, there
would be a race hazard: A notification could happen after the lock