When a thread enters wait, it must wait for other threads notify/notifyall and use notifyall to wake up.
All the threads in the wait status re-enter the lock contention queue, and notify can only wake up one. Note: at any time, only one thread can obtain the lock, that is, only one thread can run the code in synchronized. policyall only allows the thread in the wait to re-compete for the lock, however, only one lock is obtained and executed.
So what are the actual differences between policy and policyall?
The main difference is that running y is not easy to cause deadlocks, as shown in the following example.
Copy codeThe Code is as follows: public synchronized void put (Object o ){
While (buf. size () = MAX_SIZE ){
Wait (); // called if the buffer is full (try/catch removed for brevity)
}
Buf. add (o );
Y (); // called in case there are any getters or putters waiting
}
Copy codeThe Code is as follows: public synchronized Object get (){
// Y: this is where C2 tries to acquire the lock (I. e. at the beginning of the method)
While (buf. size () = 0 ){
Wait (); // called if the buffer is empty (try/catch removed for Brey)
// X: this is where C1 tries to re-acquire the lock (see below)
}
Object o = buf. remove (0 );
Y (); // called if there are any getters or putters waiting
Return o;
}
Therefore, unless you are very sure that there is no problem with policyall, you can use policyall in most cases.
For more details, see:
Http://stackoverflow.com/questions/37026/java-notify-vs-notifyall-all-over-again