This question is essentially a must-ask question when interviewing for thread-related knowledge. Therefore, it is necessary to make a more detailed summary.
Distinguish one
The first thing to understand is that these two methods come from different classes at all, and sleep comes fromthread,wait from the object class .
Sleep is a static method provided by thread that appears in that thread, and that thread "sleeps", not
Call the method of the thread to sleep, for example a thread in the call Thread B.sleep (), a thread to sleep.
Difference Two
The main difference is that the sleep method does not release the "lock", and the Wait method releases the "lock" otherwise it will form a deadlock.
Sleep does not yield system resources; When wait is a thread interaction, if thread A sends a wait to a synchronization object X
Calling the thread will enter the thread waiting for the pool to wait, wait for other threads to call Notify/notifyall wake, or after the specified time
Automatic wake-up.
It is also important to understand that either the time of the sleep setting or the wait is awakened, and the thread
Does not necessarily resume immediately, but instead triggers the "operating system to re-compete with the CPU."
Difference Three
Use a different range (this is slightly farfetched as the difference)
Wait, Notify/notifyall must be used in the synchronization control block, synchronous method. And sleep is used in any place.
Synchronized (x) {
X.notify ()
or wait ()
}
Difference Four
the code behaves that sleep must catch an exception, and wait does not need to catch the exception.
The difference between sleep and wait in Java