Multi-thread collaboration in Java is a common practice. As we all know, such collaboration is mostly implemented through wait (), notify (), or yyall, however, this implementation is worth noting. See the following example:
Thread1: synchronized (sharedmonitor) {somecondition = false; sharedmonitor. running y ();} thread2: While (somecondition) {// point 1 synchronized (sharedmonitor) {sharedmonitor. wait ();}}
If thread2 is executed first, when it is executed to point 1, the thread scheduler switches the thread to thread1, thread1 executes its settings, and executes y (). At this time, the thread switches back to thread2 to continue the execution, at this time, thread2 will enter an infinite number of busy states, because thread1 has completed running notify () before it executes wait (), so thread2 will miss this signal, this will lead to deadlocks. The solution to this problem is to prevent competition conditions in the somecondition variable. If thread2 is changed to the following, this can be achieved:
Synchronized (sharedmonitor) {While (somecondition) {sharedmonitor. Wait ();}}
If thread1 is executed first, thread2 cannot be executed no matter where the thread switches, because thread1 does not release the lock on the sharedmonitor object, thread2 can only be executed after thread1 is executed and the lock is released. When thread1 is executed, the value of somecondition is modified and this event is captured by thread2, in this way, thread2 will not enter the wait () State under the condition of somecondition = false. Instead, thread2 is added for execution, regardless of where the thread is switched, thread1 can be executed only after all the synchronized Code blocks in thread2 are executed, because thread2 has obtained the lock of the sharedmonitor object and will release the lock after the wait () execution is completed, thread2 will not miss thread1's not Ify signal.