Java Reference
In-Depth Information
Discussion
Three methods appear in java.lang.Object that allow you to use any object as a synchron-
ization target: wait() , notify() , and notifyAll() :
wait()
This causes the current thread to block on the given object until awakened by a notify()
or notifyAll() .
notify()
This causes a randomly selected thread waiting on this object to be awakened. It will then
try to regain the monitor lock.
notifyAll()
This causes all threads waiting on the object to be awakened; each will then try to regain
the monitor lock. Hopefully one will succeed.
Most programs will use notifyAll() instead of notify() , because, in waking all the
threads, the one that needs to run next will eventually get to run.
This sounds complicated, but most of the work happens inside the thread mechanism.
Do 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 or allocating objects (producing them), usually with a random delay, while
another is grabbing the objects and doing something with them (consuming them). A single-
threaded producer/consumer model is shown in Example 22-12 . As you can see, no threads
are created, so the entire program—the read() in main as well as produce() and con-
sume() —runs in the same thread. You control the production and consumption by entering a
line consisting of letters. Each p causes one unit to be produced, while each c causes one unit
to be consumed. So if I run it and type pcpcpcpc , the program alternates between producing
and consuming. If I type pppccc , the program will produce three units and then consume
them.
Search WWH ::




Custom Search