5 Difference between Sleep and Wait method with Example

Today we will share the difference between sleep and wait method in java . This is one of the most popular question of Threads topic for the java beginners. Both sleep() and wait() methods are most widely used methods in Thread programming in Java.

Read Also :  Difference between implements Runnable and extends Thread in Java


Difference between Sleep and Wait method in Java

1.  Class  belongs :  The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.

2. Context :  The wait() method can only be called from Synchronized context i.e. using synchronized block or synchronized method. The sleep() method can be called from any context.

3. Locking :  The wait() method releases the lock on an object and gives others chance to execute. The sleep() method does not releases the lock of an object for specified time or until interrupt.

4. Wake up condition :  A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be awaked by interrupt or time expires.

5. Execution :  Each object has each wait() method for inter-communication between threads. The sleep() method is static method belonging to Thread class. There is a common mistake to write t.sleep(1000) because sleep() is a class method and will pause the current running thread not t.



Example of wait() and sleep() method




import java.util.Hashtable;

public class Message {

/*** A Message class shared between Waiter and Notifier  */
   
//  volatile guarantees latest value to Waiter and Notifier. 
    public Message(String textMessage) { 

        this.textMessage = textMessage;
    } 
    
    private volatile String textMessage; 
       

    public String getTextMessage() {
     return  textMessage;
    }

    public void setTextMessage(String textMessage){
      this.textMessage = textMessage;
    }      
}


WAITER.JAVA
 
import java.util.Date;

public class Waiter implements Runnable {


/*** A Waiter class reading text message from Message class */
   
 private Message message;

 public Waiter(Message message) {
  this.message = message;
 }

 public void run() {
        // Synchronized context is necessary for wait()
 // The below synchronized block will lock message object
  
        synchronized (message) {
  try {
         System.out.println("Waiter is waiting for the Notifier at "
      + new Date());

  // Release lock on message for Notifier
         message.wait();
  }
                catch(InterruptedException interruptedException) {
    interruptedException.printStackTrace();
        }
  }
  // Synchronized block over, now message object is no more locked
  // Notifier notifies using notify() on message

  System.out.println("Waiter is done waiting at " + new Date());

  // Reading shared message set by Notifier
  System.out.println("Waiter got the message: "
    + message.getTextMessage());
 }
}

NOTIFIER.JAVA
import java.util.Date;

public class Notifier implements Runnable {


/*** A Notifier class writing Message vslue and notifies to waiter */
 private Message message;

 public Notifier(Message message) {
  this.message = message;
 }
        public void run() {
  System.out.println("Notifier is sleeping for 5 seconds at "
    + new Date());

  // Sleeping current thread for 5 seconds.
  try {
   Thread.sleep(5000);
  } catch (InterruptedException interruptedException) {
   interruptedException.printStackTrace();
  }

  // Synchronized context is necessary for notify()
  // The below synchronized block will lock message object
  synchronized (message) {
   
  // Writing into shared message object
  message.setTextMessage("Notifier took 5 seconds");
  System.out.println("Notifier is notifying waiting thread to wake up at " + new Date());

  // Notify the Waiter thread which is waiting for message
  message.notify();
  }
  // Synchronized block over, now message object is no more locked
 }
}


// ThreadDemo.java
/**
 * Main class performing sleep(), wait() and notify() over Message, Waiter and
 * Notifier classes
 */
public class ThreadDemo {

 public static void main(String[] args) {

  // Simple Message with Hello World! as text message
  Message message = new Message("Hello World!");

  // Waiter thread waiting for message from Notifier
  Waiter waiter = new Waiter(message);
  Thread waiterThread = new Thread(waiter, "Waiter Thread");
  waiterThread.start();

  // Notifier thread notifying message to Waiter
  Notifier notifier = new Notifier(message);
  Thread notifierThread = new Thread(notifier, "Notifier Thread");
  notifierThread.start();

 }
}


Output:

Waiter is waiting for the Notifier at Sat Oct 31 01:37:51 IST 2015
Notifier is sleeping for 5 seconds at Sat Oct 31 01:37:51 IST 2015
Notifier is notifying waiting thread to wake up at Sat Oct 31 01:37:56 IST 2015
Waiter is done waiting at Sat Oct 31 01:37:56 IST 2015
Waiter got the message: Notifier took 5 seconds


Similarities between wait() and sleep()

Thread state: Both the method wait() and sleep() makes the running thread into Not Runnable state.

Running time:  Both the method wait() and sleep() takes total execution time in milliseconds as an argument, after that it will be expired.

When to use wait()

difference between sleep and wait method in java
The wait() is used for multi threaded synchronization, where single resource is shared among multiple thread.

For example, file resources over network.

When to use sleep()

The wait() is used for time synchronization, where the thread actually needs a delay in background.
For example, process something on specific interval.


Recap  : Difference between Sleep and Wait in Java 




SleepWait
Class  belongs java.lang.Threadjava.lang.Object
ContextCalled from any contextOnly synchronized context
LockingDoes not release the lock
for specified time  or until
interrupt. 
Releases the lock
Wake up Condition      When time expires or
due to interruption
Awake by call to notify()
or notifyAll() method
ExecutionExecution of sleep will
pause the current running
thread not the object on which
it is called. 
Thread wait()
continues till a specific condition
holds true  



Please mentioned in the comments in case you have any questions regarding difference between sleep and wait method in java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry