Directed notifyAll()

A question if I may.

Lets suppose that my main thread creates 3 threads. These 3 threads call wait() on a certain object. Then the main thread calls notifyAll() for the same object.

How can I ensure than thread2, and only thread2, proceeds while thread1 and thread3 simply ignore the notification and go back to waiting state?

In essence, how can I direct my notification to a chosen thread?

If I am not mistaken, this would be quite simple to do in java 5. One would create different conditions and have the main thread only meet the condition on which thread2 is waiting.

However, how would I solve it in pre5?

Cheers, Vic


You should note that threads can spontaneous wake even without a notify. So you always need some kind of condition. The general form of the code is:

synchronized (lockObj) {
    while (!condition) {

There can be performance reasons to only wake threads doing specific operations. For that look into java.util.concurrent.locks, but note that it is a performance issue not a doing-the-right-thing issue.

Leave a Reply

Your email address will not be published. Required fields are marked *