Overview

This article will help you understand the stark contrast between Wait and Sleep in Java. However, before delving deep into that, let’s discuss multithreading and threads. It is a process where multiple threads are executed simultaneously. A thread is a lightweight,  part of a process, the smallest unit of processing. Java wait() and Java sleep() are different methods available in Java used to work with threads.

Java Sleep()

The Java sleep () method is related to the Thread class in Java. It is mainly used to stop the execution of the current Thread for few seconds like putting it to sleep.

 

Following are the definitions of the Java sleep() method:

1. public static native void sleep(long millisecond);  
2. public static void sleep(long milliseconds, int nanosecond);

We the sleep() method is used, the monitor does not lose its ownership. Once the wait time ends, the thread state will be then changed to a runnable state and will wait for the CPU for further execution. In simple words, the Java Sleep() method is responsible for sending a current thread into the “non-Runnable” state for a particular time.

 

See this very basic example of using the Java Sleep() method.

1.  private static void sleepExamples()
2.    throws InterruptedException {
3.    Thread.sleep(2000);
4.  System.out.println( "Thread " + Thread.currentThread().getName() + "' is now woke after sleeping for 2 second.");

 

 Output after 2 seconds:

Thread <thread name> is now woke after sleeping for 2 second.

We do not need to specify the thread with the method as the sleep() method always works with the currently executing thread of the process.

Java Wait()

The Java Wait() method is related to the Object class. It is an instance method that is used to synchronize different threads. It can be called on any object, as it is defined on java.lang.Object, but only from a synchronized block.

 

The wait() method has the following definitions:

1. wait();
2. wait(long millisecond);
3. wait(long millisecond, int nanosecond);

The Java Wait() method sends the calling thread into the waiting state. The Thread remains in the waiting state until another thread does not invoke the notify() or notifyAll() method for that object. It indicates that another thread is now ready to be synchronized. The thread currently in the waiting state then resumes the execution after obtaining the ownership of the monitor.

 

See this example of using Java wait to synchronize threads in Object obj1.

1. Private static Object obj01 = new Object();
2.
3.    synchronized (obj01) {
4.        obj01.wait(2000);
5.        System.out.println("Object '" + obj01 + "' is woken after" +
6.          " waiting for 2 second");
7.    }

 

 The following will be the output after 2 seconds:

Object obj1 is woken after waiting for 2 second

How Java Wait() and Java Sleep() Wake up?

When we use the sleep() method, a thread automatically gets started after the passed time interval is over or unless it is interrupted. In the case of wait(), the waking up process is a bit different. We have to wake the thread by calling either the notify() or notifyAll() methods on the monitor.

 

For example, see this code:

1. synchronized (a) {
2.    while (a.sum == 0) {
3.        System.out.println("Waiting for ThreadA...");
4.        a.wait();
5.    }
6.
7.    System.out.println("ThreadA is done. " +
8.      "Sum = " + a.sum);
9. }

 

Now, to wake up the waiting thread we will call notify() on the monitor:

1. int sum;
2.
3. @Override
4. public void run() {
5.    synchronized (this) {
6.        int count = 0;
7.        while (count < 100000) {
8.            sum += count;
9.            count++;
10.           }
11.           notify();
12.        }
13.   }

 

 This example will give the following output:

Waiting for ThreadA …
ThreadA is done. Sum = 53453435

Similarities between Java Wait() and Java Sleep()

Before understanding the differences between Java wait() and Java sleep(), we need to understand the similarities between them. Both the Java Wait() and Java Sleep() methods are the native methods that send the current Thread into the Non-Runnable State.

 

See this code example of Java wait() and Java Sleep() method performing the same task of delaying the thread for 2 seconds,

1. class SleepWaitSimilarities {   
2.   private static Object obj01 = new Object();   
3.   public static void main(String[] args)throws InterruptedException   
4.   {    
5.     //using sleep method to pause process for two second  
6.     Thread.sleep(2000);   
7.
8.     //print the output message  
9.     System.out.println( Thread.currentThread().getName() +   
10.    " Thread woke up after two second");   
11.
12.    //first, we need to  create synchronized context from which we call Wait() method  
13.    synchronized (obj)    
14.   {   
15.     //using wait() method to set obj in waiting state for two seconds  
16.     obj.wait(2000);  
17. 
18.     System.out.println(obj + " Object is in waiting state and woke up after 2 seconds");   
19.   }   
20. }   
21.}

 

 Output after 2 seconds will be:

<thread name>Thread woke up after two second
<object name>Obj Object is in waiting state and woke up after 2 seconds

 

Java Sleep() VS Java Wait()

Now, as they seem and work quite similarly, what could be the difference between them? Other than sending a thread to a non-runnable state they both methods have some significant differences.

Following are all the differences between Java Sleep() and Java Wait() methods:

Belongs to different Classes

The Wait() method is related to the Object class whereas The Sleep () method is related to the Thread class.

Ownership

The Java Sleep() method does not release the ownership of an object during synchronization until there is an interruption or the time has ended. The Java Wait() method, on the other hand, releases the ownership to let other objects execute till notify() or notifyAll() method is invoked on the monitor.

Different types of methods

The Sleep() method is a static method whereas the Wait() method is not static that is why it needs an object to invoke it.

Different completion process

The Sleep() method execution is completed when it is interrupted by a thread or the time of sleep method is expired but the Wait method execution is completed when it is interrupted by the notify() or notifyAll() method.

Restriction in Calling the method

The Wait() method can only be called from the Synchronized context.  There is no such restriction in calling the Sleep() method. It can be called from the outside the Synchronized context.

Different Execution

As mentioned before, the sleep() method is always executed on the current thread whereas the wait method is executed on the object.

Overloaded methods of Java Wait and Java sleep

The Sleep() method consist of two overloaded methods, which are as follows:

  1. sleep(long milliseconds, int nanoseconds)
  2. sleep(long milliseconds)

The Wait() method has the following three overloaded methods:

  1. Wait()
  2. wait(long timeout, int nanoseconds)
  3. wait(long timeout)

The nanosecond argument present in both methods fulfills the purpose of increasing the accuracy of the time interval.

The wait method can also be called without any parameter as it will release the thread when another thread will call the notify() method. The timeout is for a relatively long period of wait time.  Both of these overloaded functions are not present with Java Sleep() method.

Different Constructors

The constructor of the Wait() method is defined like this:

  • public final void wait(long timeout)

And this is the constructor of the Sleep () method:

  • public static void Sleep(long millis) throws Interrupted_Execption

The difference is due to the nature of the method and the exception handling.

Different Exceptions

The Java static method throws the InterruptedException to deal with an interrupt. On the contrary, the wait method throws the following two more exceptions along with InterruptedException,

  • IllegalArgumentException
  • IllegalMonitorStateException

Logic difference:

When multiple threads want to use the same resource one by one, then we use the Java wait() method. On the other hand, when a thread does not want to perform any task, it is then sent to the un-runnable state, we must use the Java sleep() method.

Conclusion:

In the article above, we have briefly discussed multithreading in Java and how threads are processed. We have also covered how Java Sleep() and Java Wait() work and the similarities between them. Later, we covered all the differences between these two methods. Both Java Sleep() and Java Wait() methods seem the same by their names but only an experienced Java developer can tell the difference.

See Also: Guide To Java 8 forEach Method With Example

Although these methods are mostly used in multithreading and more towards operating system tasks rather than in applications development or web development, it’s important for Java developers to be aware of them.

Author

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.

Write A Comment