![]() |
VOOZH | about |
In Java, wait() and sleep() are commonly used methods that pause the execution of a thread. Although both seem similar, they differ significantly in behavior, usage, and purpose, especially in multithreaded environments.
The sleep() method is a static method of the Thread class. It temporarily pauses the execution of the currently executing thread for a specified period of time.
public static void sleep(long millis) throws InterruptedException
Example:
Output:
Thread going to sleep
Thread woke up
Explanation: The current thread pauses execution for 2 seconds and then resumes automatically after the specified time.
The wait() method is a non-static method of the Object class. It causes the current thread to wait until another thread invokes notify() or notifyAll() on the same object.
public final void wait() throws InterruptedException
Example:
Thread waiting Thread notifying Thread resumed
Explanation: The first thread waits until the second thread calls notify() on the same object. During waiting, the lock is released and later reacquired.
👁 Difference-between-wait-and-sleep-in-JavaThe diagram illustrates how a thread moves between different states when wait() and sleep() methods are used.
| Wait() | Sleep() |
|---|---|
| Wait() method belongs to Object class. | Sleep() method belongs to Thread class. |
| Wait() method releases lock during Synchronization. | Sleep() method does not release the lock on object during Synchronization. |
| Wait() should be called only from Synchronized context. | There is no need to call sleep() from Synchronized context. |
| Wait() is not a static method. | Sleep() is a static method. |
Wait() Has Three Overloaded Methods:
| Sleep() Has Two Overloaded Methods:
|
| public final void wait(long timeout) | public static void sleep(long millis) throws Interrupted_Execption |