Thread Communication: wait( ) and notifyAll( )
Problem
The synchronized
keyword lets you lock out
multiple threads, but
doesn’t give you much communication between them.
Solution
Use wait( )
and notifyAll( ). Very carefully.
Discussion
Three methods appear in
java.lang.Object that allow you to use any
object as a synchronization
target: wait( ),
notify(
), and notifyAll( ).
-
wait( ) Causes the current thread to block in the given object until awakened by a
notify( )ornotifyAll( ).
-
notify( ) Causes a randomly selected thread waiting on this object to be awakened. It must then try to regain the monitor lock. If the “wrong” thread is awakened, your program can deadlock.
-
notifyAll( ) Causes all threads waiting on the object to be awakened; each will then try to regain the monitor lock. Hopefully one will succeed.
The mechanism is a bit odd: there is no way to awaken only the thread
that owns the lock. However, that’s how it works, and
it’s the reason almost all programs use notifyAll( ) instead of notify( ). Also note that
both wait( ) and the notification methods can be
used only if you are already synchronized on the
object; that is, you must be in a
synchronized method within, or a code block synchronized on, the
object that you wish your current thread to wait( ) or notify( ) upon.
For a
simple
introduction to wait( ) and notify( ), I’ll use a simple Producer-Consumer model. This pattern can be used to simulate a variety of real-world situations in which one object is creating ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access