Thread Communication: wait( ) and notifyAll( )
keyword lets you lock out
multiple threads, but
doesn’t give you much communication between them.
notifyAll( ). Very carefully.
Three methods appear in
java.lang.Object that allow you to use any
object as a synchronization
Causes the current thread to block in the given object until awakened by a
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.
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
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.
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 ...