2020-09-15: What are the differences between wait() and sleep() in java?

Fu Ge answer 2020-09-15: #福大Architects Daily One Question#

1. Thread status. The thread status of wait() is TimedWaiting and Waiting. The thread state of sleep() is Waiting.
2. Specify the time. wait() can specify the time or not. sleep() must specify the time.
3. Release the lock. wait() releases the lock and joins the waiting queue, which is often used for inter-thread interaction. sleep() does not release the lock and is often used to suspend execution.
4. Synchronization block. wait() needs to be used in a synchronized block, otherwise an IllegalMonitorStateException will be thrown. No need for sleep().
5. In the category. wait() is a method in Object. sleep is a static method in Thread.
6. Wake up. wait() needs to be awakened (not specified time needs to be awakened by others), notify(), notifyAll(), interrupt(). Sleep() does not need to be awakened (it exits blocking after sleep), time is up or interrupt().
7. Catch the exception. wait() does not need to catch the exception without specifying the time, and it needs to catch the exception with the specified time. sleep() needs to catch exceptions.


comment

Guess you like

Origin blog.csdn.net/weixin_48502062/article/details/108610035
Recommended