Difference between Wait and Sleep in Java
In Java, wait and sleep are the concept of multithreading. Wait and Sleep are the methods used to pause a process for few seconds and go a thread in the waiting state, respectively. Let’s understand both of them one by one to get more information about them.
Sleep()
The Sleep () method is related to the Thread class that is used to stop the execution of the current Thread for few seconds. The Sleep () method takes the sleeping time in milliseconds. The monitor’s ownership is not lost when we use the Sleep () method and start the execution again from where it stops. In simple words, the Sleep() method is responsible for sending the current Thread into the “Non Runnable” state.
Wait()
The Wait() method is related to the Object class. The Wait() method is responsible for sending the calling thread into the waiting state. The Thread remains in the waiting state until another thread doesn’t invoke the notify() or notifyAll() method for that object. The Thread resumes the execution after obtaining the ownership of the monitor.
Before understanding the differences between both of them, let’s understand the similarities between them. So, both the Wait() and Sleep() methods are the native methods that make the current Thread go into the Non-Runnable State.
Let’s take an example to understand the similarities of both of them.
WaitSleepSimilaritiesExample.java
Output
Difference b/w Wait() and Sleep()
Let’s understand the difference between Wait () and Sleep() method:
Sr. No. | Wait() | Sleep() |
---|---|---|
1. | The Wait() method is related to the Object class. | The Sleep () method is related to the Thread class. |
2. | The Sleep () method does not release the lock on the object during Synchronization. | |
3. | It is not a static method. | It is a static method. |
4. | At the time of the Synchronization, the Wait() method releases obj. | At the time of the Synchronization, the Sleep() method doesn’t release the obj, i.e., lock. |
5. | We can call the Wait () method only from the Synchronized context. | We can call the Sleep () method from outside the Synchronized context. |
6. | The Sleep() method has two overloaded methods, which are as follows:
| The Sleep() method has three overloaded methods, which are as follows:
|
7. | The constructor of the Wait() method is defined in the following way: public final void Wait(long timeout) | The constructor of the Sleep () method in the following way: public static void Sleep (long millis) throws Interrupted_Execption |