Java Reference
In-Depth Information
The output is the most common I got from running the program many times (aside from
the random numbers changing), but as with any multithreaded application, the output
might vary depending on the environment.
The
notifyAll
Method
If your program has multiple threads waiting for a call to
notify
, then you can use the
notifyAll
method of
Object
. The
notifyAll
method wakes up all threads waiting for an
object's lock.
Keep in mind that all of these threads that are awakened are all competing for the same
object's lock before they can proceed. However, they are no longer in the
WAITING
or
TIMED_WAITING
state because they have transitioned to the
BLOCKED
state, making each
thread one step closer to
RUNNABLE
, as Figure 5.5 shows.
The producer and consumer in the stack example could easily be switched. If a thread
attempts to push an
int
on a full stack, it could wait for another thread to pop an
int
off the stack, assuming the popping thread calls
notify
on the stack after each pop. For
example, assuming the pushing thread is waiting for a pop, the following statements add a
call to
notify
to the
Consumer
class on line 19 on the stack object after a pop occurs:
10. synchronized(stack) {
11. int x = stack.pop();
12. if(x == -1) {
13. try {
14. System.out.println(“Waiting...”);
15. stack.wait();
16. }catch(InterruptedException e) {}
17. } else {
18. System.out.println(“Just popped “ + x);
19. stack.notify();
20. }
21. }
Having a thread invoke both
wait
and
notify
is a fairly common occurrence in
producer/consumer situations where threads rely on each other to complete certain tasks.
The
notify
method wakes a single thread that is waiting on the object's
monitor. If multiple threads are waiting, you do not have any control over
which ones are chosen to be awakened. The thread chosen is arbitrary and
is based on the JVM implementation that the code is running in.
Search WWH ::
Custom Search