Home >Java >javaTutorial >The difference between sleep and wait in JAVA
wait() method means that the current thread allows itself to temporarily give up the synchronization resource lock so that other threads waiting for the resource can obtain the resource and run. Only by calling notify() method, the thread that previously called wait() will be released from the wait state, and can participate in the competition for the synchronization resource lock, and then be executed.
The sleep() method can be used anywhere; the wait() method can only be used in synchronized methods or synchronized blocks; (Recommended learning: java course )
sleep() is a method of the thread class (Thread). The call will suspend the thread for the specified time, but the monitoring will still be maintained, the object lock will not be released, and it will automatically resume when the time expires;
wait() is a method of Object. The call will give up the object lock and enter the waiting queue. It will not enter the lock pool until notify()/notifyAll() is called to wake up the specified thread or all threads. It will not enter until the object lock is obtained again. Running status;
The life cycle diagram of threads in Java is as follows:
The above is the detailed content of The difference between sleep and wait in JAVA. For more information, please follow other related articles on the PHP Chinese website!