Generally, there is a need for coordination between multithreading. For example, a browser's thread that displays a picture Displaythread wants to perform the task of displaying a picture, and must wait for the download thread downloadthread to download the picture. If the picture has not been downloaded, displaythread can pause, when Downloadthread completed the task, and then notify Displaythread "picture ready, you can show", then Displaythread continue to execute.
The above logic is simply: if the condition is not satisfied, then wait. When the condition is satisfied, the thread that waits for the condition is awakened. In Java, the implementation of this mechanism relies on wait/notify. The wait mechanism is closely related to the lock mechanism. For example:
synchronized(obj) {
while(!condition) {
obj.wait();
}
obj.doSomething();
}
When thread a obtains the obj lock, the discovery condition condition is not satisfied and cannot proceed to the next processing, so thread A is wait ().
In another thread B, if B changes certain conditions so that thread A's condition condition is satisfied, thread A can be awakened:
synchronized(obj) {
condition = true;
obj.notify();
}
The concepts that need to be noted are:
You must obtain the obj lock, which must be written in the synchronized (obj) {...} code snippet, before you call obj's Wait (), notify () method.
After the call to Obj.wait (), thread a releases the lock on obj, otherwise thread B cannot get the obj lock and cannot wake a in the synchronized (obj) {...} code snippet.
When the Obj.wait () method returns, thread a needs to acquire the OBJ lock again in order to continue execution.
If a1,a2,a3 are all in obj.wait (), then B calls Obj.notify () can only wake one of the A1,A2,A3 (which is determined by the JVM).
Obj.notifyall () can wake up all a1,a2,a3, but to continue executing the next Statement of Obj.wait (), the obj lock must be obtained, so A1,A2,A3 has only one chance to get the lock to continue execution, such as A1, The rest needs to wait for A1 to release the obj lock before proceeding.
When B calls Obj.notify/notifyall, B is holding the obj lock, so a1,a2,a3 is awakened, but the obj lock is still not available. Until B exits the synchronized block and releases the obj lock, one of the A1,A2,A3 has the opportunity to obtain the lock to continue execution.