Java stereotyped - wait, sleep and park

sleep(), wait(), and park() can all make the thread enter the waiting state, but the three methods are somewhat different in use and function.

common ground:

  • The effects of wait(), wait(long) and sleep(long) are to let the current thread temporarily give up the right to use the CPU and enter the blocking state
  • They can all be interrupted to wake up
  • Both are native methods
  • Threads that execute sleep(long), wait(long), and parkUntil(long) will wake up after waiting for the corresponding milliseconds

difference:

  • Method attribution is different
    • sleep(long) is a static method of Thread
    • wait(), wait(long) are member methods of Object, each object has
    • park() belongs to the LockSupport class
  • Wake up at different times
    • wait(long) and wait() can also be woken up by notify, if wait() does not wake up, it will wait forever
    • Unpark can specify to wake up a blocked thread, and the operation is more precise. The operations of notify (random wakeup) and notifyAll (all wakeup) may not be suitable for some scenarios
  • Different lock characteristics
    • The call of the wait method must first obtain the lock of the wait object, but there is no such restriction for park and sleep
    • After the wait method is executed, the object lock will be released, allowing other threads to obtain the object lock, while sleep and park will not release the object lock if they are executed in the synchronized code block

insert image description here

If you are interested in learning more about it, please visit my personal website: Yetong Space

Guess you like

Origin blog.csdn.net/tongkongyu/article/details/129344043