notify and notifyAll

notify results in a single thread acquiring a lock whereasnotifyAll results in all the threads competing for the lock and one of them acquiring it

so any way only one thread is able to acquire the lock, so why do we need notfyAll at all.

Is there something more to it.

[302 byte] By [jaaya] at [2007-10-2 20:17:19]
# 1

Yes, there's a good reason to have notifyAll. notify will only wake one thread up, the others will still be waiting for something to happen. notifyAll will wake all threads up so that they know that something has happened (that is all threads will continue to execute when they can acquire the lock)

Kaj

kajbja at 2007-7-13 22:59:46 > top of Java-index,Java Essentials,New To Java...
# 2

It can all be illustrated by an example:

public class Test {

public static void main(String[] args) throws Exception {

final Object lock = new Object();

class R implements Runnable {

public void run() {

synchronized (lock) {

try {

lock.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

System.err.println("Thread " + toString() + " ended");

}

}

synchronized (lock) {

new Thread(new R()).start();

new Thread(new R()).start();

new Thread(new R()).start();

}

Thread.sleep(1000);

synchronized (lock) {

lock.notify();//Change this line to notifyAll

}

System.out.println("Main thread ended");

}

}

Kaj

kajbja at 2007-7-13 22:59:46 > top of Java-index,Java Essentials,New To Java...
# 3
There is a difference whether all waiting threads are waken and compete for the lock or only one. Only one is able to acquire the lock at a given moment, but later on the two scenarios differ.
BIJ001a at 2007-7-13 22:59:46 > top of Java-index,Java Essentials,New To Java...