Java concurrent programming wait (), notify () and notifyAll ()

Java has a built-in wait mechanism to allow threads to become non-operational while waiting for signals. The java.lang.Object class defines three methods, wait (), notify (), and notifyAll () to implement this waiting mechanism.

Once a thread calls the wait () method of any object, it will become in a non-running state until another thread calls the notify () method of the same object. In order to call wait () or notify (), the thread must first acquire the lock on that object. That is, the thread must call wait () or notify () in the synchronization block.

wait: indicates that thread A holding the object lock is ready to release the object lock permission, release cpu resources and enter wait.
notify : indicates that the thread A holding the object lock is ready to release the permission of the object lock and informs the jvm to wake up a thread X competing for the object lock. After the thread A synchronized code scope ends, thread X directly obtains the object lock permission, and other competing threads continue to wait (even if thread X is synchronized and the object lock is released, other competing threads still wait until a new notify, notifyAll is called).
notifyAll: indicates that the thread A holding the object lock is ready to release the object lock permission, and informs the jvm to wake up all the threads competing for the object lock. After the scope of the thread A synchronized code ends, the jvm assigns the object lock permission to a thread X through the algorithm All awakened threads no longer wait. After the scope of thread X synchronized code ends, all previously awakened threads are likely to obtain the object lock permission, which is determined by the JVM algorithm.

example:

 

Note: This article is original and cannot be reproduced on any platform without permission. If you need to reprint,
please contact the author ~ follow WeChat public number: knowledge training camp, you can communicate with Java qun: 16844592, for more information ~

Guess you like

Origin www.cnblogs.com/bootcamp/p/12738251.html