To address access control issues, Java introduces a blocking mechanism. Blocking refers to pausing the execution of a Java thread synchronization to wait for a condition to occur (such as a resource is ready).
sleep (): allows you to specify a period of time in milliseconds as a parameter, which causes the thread to enter a blocking state within a specified time, cannot get CPU time, the specified time is over, and the thread re-enters the executable state. Typically, sleep () is used when waiting for a resource to be ready: After the test discovery condition is not met, let the thread block for a period of time and then re-test until the condition is satisfied.
suspend () &resume (): Two methods are used, suspend () causes the thread to go into a blocking state and does not automatically recover, it must be called by its corresponding resume () in order to allow the thread to re-enter the executable state. Typically, suspend () and resume () are used when waiting for the result of another thread: After the test finds that the result has not yet been generated, the thread is blocked and the other thread produces the result, calling resume () to restore it.
yield ():yield () causes the thread to discard the current CPU time, but does not cause the thread to block, that is, the thread is still in an executable state, and the CPU time may be split again at any time. The effect of calling yield () is equivalent to the scheduler thinking that the Java thread synchronization has taken enough time to go to another thread.
Wait () ¬ify (): Two methods are used, and wait () causes the thread to enter a blocking state, which has two forms, one that allows specifying a period of time in milliseconds as a parameter, and the other without parameters when the corresponding notify () The Java thread synchronizes to the executable state when it is called or exceeds the specified time, and the latter must be called by the corresponding notify (). Tip : (1) Use must be synchronized, or immediately throw an exception. (2) Wait () ¬ify () is the method of the object.
At first glance they have nothing to do with the suspend () and the Resume () methods, but in fact they are quite different. The core of the difference is that all of the methods described earlier, blocking will not release the lock used (if occupied), and this pair of methods will release the lock occupied .
During the execution of the synchronized code, the thread can call the object's Wait () method, release the object lock flag, enter the wait state, and call the Notify () or the Notifyall () method to notify other threads that are waiting. Notify () notifies the first thread in the wait queue, and Notifyall () notifies all threads in the wait queue.
(RPM) Java thread synchronization blocking, sleep (), suspend (), resume (), yield (), wait (), notify ()