The sleep () method suspends the thread for a period of time, and the Wait () method blocks the thread until it is woken up or the wait time times out.
The difference is specific as follows:
1 different principles
The sleep () method is a static method of the thread class that causes the thread to pause for a period of time until the timer ends and the thread automatically "wakes up". The wait () method is a non-static method of the object class that is used for inter-thread communication so that the thread that currently owns the lock waits until another thread calls the Notify () method (or Notifyall () method). You can also automatically wake up the thread by setting the time-out to be timed.
2 different handling mechanisms for locks
The sleep () method does not involve communication between threads and does not release locks. The wait () method causes the thread to release the lock it occupies.
3 different areas of use
The sleep () method can be placed anywhere, and the Wait () method can only be placed in the synchronization block.
4 whether the catch exception is different
The sleep () method must catch exceptions, and wait (), notify (), and Notifyall () methods do not need to catch exceptions. During the thread sleep process, it is possible for other objects to call its interrupt () method, throwing a interruptedexception exception.
In summary, it is recommended to use the wait () method because the sleep () method does not release the lock and is prone to deadlock problems.
Resources
"Java Programmer interview written book" P149-150
The difference between the Java multithreaded sleep () method and the Wait () method