What is the difference between sleep() and wait() in Java interview questions?

What is the difference between sleep() and wait()?

1. The sleep() method is a static method of the thread class Thread. It allows the calling thread to enter the sleep state and gives the execution opportunity to other threads. After the sleep time is over, the thread enters the ready state and competes with other threads for CPU execution time.

Because sleep() is a static (static modified) method, it cannot change the machine lock of the object. When the sleep method is called in a synchronized block, although the thread enters the dormant state, the machine lock of the object is not released and other threads cannot access it. This object.

2. Wait() is a method of the Object class. When a thread executes to the wait() method, it enters a waiting pool related to the object, and at the same time releases the lock of the object, which can be accessed by other threads. You can use notify , And notifyAll method to wake up waiting threads.

wait(), notify(), notifyAll() can only be used in synchronous control methods or synchronous control blocks, while sleep() can be used anywhere.

Sleep() must catch exceptions, while wait(), notify(), notifyAll() do not need to catch exceptions.

Guess you like

Origin blog.csdn.net/weixin_44296929/article/details/108324925