The difference between sleep and wait is that sleep does not release the lock, and the pause of sleep is different from that of wait. OBJ. Wait will make the thread enter the waiting set of the OBJ object and wait for awakening.
However, both wait () and sleep () can interrupt the pause state of the thread through the interrupt () method, so that the thread immediately throws interruptedexception.
If thread a wants to terminate thread B immediately, it can call the interrupt method for the thread instance corresponding to thread B. If thread B is wait/sleep/join at the moment, thread B will immediately throw interruptedexception and directly return in catch () {} to end the thread safely.
It should be noted that interruptedexception is thrown by the thread itself from the internal, not by the interrupt () method. When interrupt () is called for a threadCodeThe thread will not throw interruptedexception. However, once the thread enters wait ()/sleep ()/join (), interruptedexception is immediately thrown.
1. Sleep () method Introduction
The sleep () method is used to stop a thread for a period of time. After the sleep interval expires, the thread may not resume execution immediately. This is because at that time, other threads may be running and not scheduled to give up execution, unless
(A) The waking thread has a higher priority.
(B) The Running thread is blocked for other reasons.
2. Wait () method Introduction
When wait () is a thread interaction, if the thread sends a wait () call to a synchronization object X, the thread will pause the execution and the called object will enter the waiting state, wait until the wake-up or wait time is reached. When wait () is called, the thread releases the lock mark it occupies, so that other synchronized data in the thread's object can be used by other threads.
3. Differences between wait () and notify ()
Wait () and notify () will operate on the & ldquo; lock Mark & rdquo; of the object, so they must be called in the synchronized function or synchronized block. If the call is performed in the non-synchronized function or the non-synchronized block, the illegalmonitorstateexception exception may occur at runtime although the compilation is successful.