Difference Between Wait and Sleep in Java

In this post, we will see differences Between Wait and Sleep in Java.


Wait vs Sleep

Sleep method is used to pause a thread for some time whereas wait causes current thread to wait until another thread calls notify and notifyAll().

Sleep is static method of Thread class and it causes current thread to sleep.

One more important point is wait needs to be called from synchronized method or block otherwise it will throw IllegalMonitorStateException in java but there is no such criterion for sleep method.


Sleep example


Wait example


Differences between wait and sleep in java

Synchronized context

  • wait needs to be called from Synchronized state.
  • Sleep does not need to be called from Synchronized state

Lock

  • When you call wait on any object, it releases lock on that object
  • Sleep does not release any lock

Type of method

  • Wait is instance method of Object class
  • Sleep is static method of Thread class

Wake up condition

  • Until call notify or notify all
  • Until time expires or calls interrupt

Leave a Reply

Your email address will not be published. Required fields are marked *