What is the Difference Between sleep and wait in Java?

🆚 Go to Comparative Table 🆚

The main difference between sleep() and wait() in Java is that sleep() is a static method of the Thread class, while wait() is a non-static method of the Object class. Additionally, wait() releases the lock during synchronization, whereas sleep() does not release any lock while waiting.

Here are some key differences between sleep() and wait():

  • Purpose: sleep() is used to pause the execution of the current thread for a specified time in milliseconds. On the other hand, wait() is used for inter-thread communication and puts the calling thread into a waiting state until another thread calls notify() or notifyAll().
  • Lock Release: When a thread calls sleep(), it does not release the lock. If the thread is in a synchronized block or method, no other thread can enter that block or method. In contrast, when a thread calls wait(), it releases the lock, allowing other threads to enter the synchronized block or method.
  • Usage: sleep() is typically used for time-synchronization, while wait() is used for multi-thread synchronization.
  • Method Call: sleep() is called on the Thread class, always using the currently executing thread. In contrast, wait() is called on an object, and the current thread must synchronize on the lock object.

In summary, sleep() is used to pause the execution of a thread for a specific time, while wait() is used for inter-thread communication and synchronization, releasing the lock during the waiting period.

Comparative Table: sleep vs wait in Java

Here is a table comparing the differences between the sleep() and wait() methods in Java:

Method Description Who Is Calling Purpose Lock on Object
sleep() Pauses the execution of the current thread for a specified time in milliseconds Thread class Causes the current thread to go into the "Non Runnable" state No, it keeps the lock on the object
wait() Causes the current thread to go into the waiting state until another thread invokes the notify() or notifyAll() method Object class Causes the current thread to go into the waiting state Yes, it releases the lock on the object

In summary:

  • sleep() is a method of the Thread class that pauses the execution of the current thread for a specified time in milliseconds.
  • wait() is a method of the Object class that causes the current thread to go into the waiting state until another thread invokes the notify() or notifyAll() method.
  • The sleep() method does not release the lock on the object during synchronization, while the wait() method releases the lock on the object during synchronization.