When a thread enters a wait, it must be notify/notifyall by other threads, using Notifyall, to wake
All threads in the wait state are brought back into the lock contention queue, and notify can only wake one. Note that only one thread can get the lock at any time, that is, only one thread can run the code in synchronized, Notifyall just let the wait thread regain the lock contention, but only one will get the lock and execute it.
So what's the difference between notify and notifyall in terms of effect?
The main effect difference is that notify is not used easily to lead to deadlocks, such as the examples mentioned below.
Copy Code code as follows:
Public synchronized void put (Object o) {
while (Buf.size () ==max_size) {
Wait (); Called if the ' is full ' (try/catch removed for brevity)
}
Buf.add (o);
Notify (); Called in case there are any getters or putters waiting
}
Copy Code code as follows:
Public synchronized Object get () {
Y:this is where C2 tries to acquire the lock (i.e. in the beginning of the method)
while (Buf.size () ==0) {
Wait (); Called If the empty (Try/catch removed for brevity)
X:this is where C1 tries to re-acquire the lock (in the below)
}
Object o = buf.remove (0);
Notify (); Called if there are any getters or putters waiting
return o;
}
So unless you're pretty sure that notify is not a problem, most of the cases are notifyall.
For more detailed information, refer to:
Http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again