Home > Java > JavaBase > What is the difference between wait and sleep in java?

What is the difference between wait and sleep in java?

青灯夜游
Release: 2019-12-27 15:31:17
Original
4520 people have browsed it

What is the difference between wait and sleep in java?

sleep:

The sleep method belongs to the method in the Thread class, which means to put a thread into sleep state and wait for a certain period of time before automatically waking up. to enter the runnable state, it will not enter the running state immediately, because the thread scheduling mechanism also takes time to resume the running of the thread. After a thread object calls the sleep method, it will not release all the object locks it holds, so it It will not affect the operation of other process objects. However, during the sleep process, its interrupt() may be called by other objects, resulting in an InterruptedException exception. If your program does not catch this exception, the thread will terminate abnormally and enter the TERMINATED state. If your program catches this exception, Exception, then the program will continue to execute the catch statement block (and possibly the finally statement block) and subsequent code.

#wait:

wait is a member method belonging to Object. Once an object calls the wait method, the notify() and notifyAll() methods must be used to wake up the process; If a thread owns a synchronization lock on one or more objects, then after calling wait(), the thread will release all synchronization resources it holds, not limited to the object on which the wait() method was called. The wait() method may also be generated by other objects calling the interrupt() method during the wait process.

The difference between sleep and wait methods is:

● Sleep comes from the Thread class, and wait comes from the Object class

● The sleep method does not release the lock. The wait method releases the lock so that other threads can use the synchronization control block or method

●wait, notify and notifyAll can only be used in the synchronization control method or synchronization control block, while sleep can be used anywhere

● Sleep must catch exceptions, while wait, notify and notifyAll do not need to catch exceptions

Recommended learning: Java video tutorial

The above is the detailed content of What is the difference between wait and sleep in java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template