[JAVAee] The difference between the wait method and the sleep method

The most obvious difference is that the wait method needs to be used with the synchronized keyword. The use of the sleep method does not require

wait is a method of Object class, sleep is a static method of Thread class

method illustrate

public static void sleep(long millis) throws interruptedException

Causes the currently executing thread to suspend (temporarily halt execution) for the specified number of milliseconds, depending on the precision and accuracy of system timers and the scheduler. The thread does not lose ownership of any displays.

public final void wait( ) throws interruptedException

Causes the current thread to wait until another thread calls the object's notify() method or notifyAll() method.

③The purpose of their use is different in nature. The sleep method is for a single thread to simply let it sleep\pause for a certain period of time. When the time comes, it will resume operation and continue to execute the following code.

For wait, it is more a tool for communication and cooperation between different threads, because the wait method is generally used with the notify or notifyAll method. A certain connection between the two threads is required.

Guess you like

Origin blog.csdn.net/weixin_67719939/article/details/131879445