0

What is the difference between sleep() and wait() method?

Both method are pause the thread from running. So why their are two methods.is their implementation are different?

23rd Aug 2020, 2:36 PM
Bhumesh Polaswar
Bhumesh Polaswar - avatar
2 Answers
+ 8
Bhumesh Polaswar The sleep() method is defined in Thread class and it is a static method so we can call it by Thread class. The wait() method exists in Object class and it is a non-static method so we can call it by the object. Context The wait() method is called only from the synchronized context that is synchronized block or synchronized method. The sleep() method can be called from any context. Call As we discuss the wait() method is defined in Object class. So, it operates on Object and we can call the wait() method only by thread object which we want to make wait. A sleep() method operates on current thread and when we call the sleep() method, the JVM assume we want to sleep the thread in which method is placed.   State change When we use the sleep() method, it pauses the execution of the current thread and moves that thread in TIMED_WAITING state. After the competition of waiting time, the thread moves again in RUNNABLE state. https://javagoal.com/difference-between-wait-and-sleep-in-java/
28th Aug 2020, 1:41 AM
Raina Dhankhar
Raina Dhankhar - avatar
+ 4
The major difference is to wait() to release the lock or monitor while sleep() doesn't release any lock or monitor while waiting. Wait() is used for inter-thread communication while sleep() is used to introduce pause on execution. for more info visit👇 https://stackoverflow.com/questions/1036754/difference-between-wait-and-sleep
23rd Aug 2020, 2:41 PM
Arsenic
Arsenic - avatar