Difference between Wait and Sleep in Java

JavaObject Oriented ProgrammingProgramming

Wait() - The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify() method or the notifyAll() method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

Sleep() - This method causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors. It sends the current thread into the “Not Runnable” state for a specified amount of time.

Sr. No.KeyWaitSleep
1
Class 
Wait() method belongs to Object class 
Sleep() method belongs to Thread class 
2
Lock Release 
Wait() releases the lock on an object 
It does not release lock on an object 
3
Calling context
Wait() can be called on object itself 
Sleep() can be called on thread 
4.
Wake-up condition
until call notify(), notifyAll() from object
until at least time expire or call interrupt
5
spurious wakeups 
Program can get spurious wakeups 
It will not get spurious wakeups.

Example of SynchronizedMap

synchronized(lockedObject){
   while(condition == true){
      lockedObject.wait() //releases lockedObject lock
   }
   Thread.sleep(100); //puts current thread on Sleep
}
raja
Published on 18-Nov-2019 07:01:05
Advertisements