The difference between Wait(), sleep() and yield() methods

Differences between Wait(), sleep() and yield() methods

1. Different classes: wait() is a non-static method in Object class; sleep() is a static method in Thread class; yield() is also in Thread class static method.

2. Different functions: wait() is used for thread synchronization or communication between threads; sleep() is used to sleep the current thread and is automatically awakened at a specified time; yield() temporarily suspends the currently executing thread to Gives a waiting thread of the same priority a chance to execute (if the waiting thread has a lower priority, the current thread continues to execute).

3. Release resources: wait() will release the lock and monitor occupied by the thread; sleep() will release the lock occupied by the thread, but not the monitor; yield() will only release the CPU occupied by the thread.

4. Different application scenarios: wait() is suitable for synchronous code blocks; sleep() sleeps the current thread, and there are no restrictions on application scenarios; yield() suspends the current thread, and there are no restrictions on application scenarios.

5. The state after being awakened is different: after wait() is awakened by notify() or notifyAll(), it first enters the blocking state (the lock is obtained first), and then enters the ready state; after sleep() is awakened, it enters the ready state; yield () does not need to wake up, it is always in the ready state, and continues to run after obtaining the CPU.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326232002&siteId=291194637