What is the difference between a wait()
and sleep()
in Threads?
Is my understanding that a wait()
-ing Thread is still in runni
Here, I have listed few important differences between wait()
and sleep()
methods.
PS: Also click on the links to see library code (internal working, just play around a bit for better understanding).
wait()
method releases the lock. wait()
is the method of Object
class.wait()
is the non-static method - public final void wait() throws InterruptedException { //...}
wait()
should be notified by notify()
or notifyAll()
methods.wait()
method needs to be called from a loop in order to deal with false alarm.
wait()
method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException
sleep()
method doesn't release the lock.sleep()
is the method of java.lang.Thread
class.sleep()
is the static method - public static void sleep(long millis, int nanos) throws InterruptedException { //... }
sleep()
is completed.sleep()
better not to call from loop(i.e. see code below).sleep()
may be called from anywhere. there is no specific requirement. Ref: Difference between Wait and Sleep
Code snippet for calling wait and sleep method
synchronized(monitor){
while(condition == true){
monitor.wait() //releases monitor lock
}
Thread.sleep(100); //puts current thread on Sleep
}