In Multithreading, both wait() and sleep() methods are used to make a thread to sleep. The main difference between both of them is, wait() puts a thread to sleep and forces it to move to suspended state, whereas, sleep puts a thread sleep for specified milliseconds.
Difference between wait() and sleep() in Tabular form
Sleep Method | Wait Method |
---|---|
It puts a thread to sleep for some time and makes that thread to automatically wake up after specified time ends | It forces a thread to sleep until notify() gets triggered |
It doesn't force a thread to release its lock before completing its task | It forces a thread to release its lock before completing its task |
It is not mandatory to define it within synchronised block | It is mandatory to define it within synchronised block |
It halts a thread execution temporarily | It halts a thread execution permanently |
It is invoked on thread | It is invoked on object |
A thread awakes automatically or by interrupt() | A thread awakes by notify() and notifyAll() |
It controls a thread's execution time | It controls multi-thread synchronization |
wait() Method
Wait method makes a thread sleep and forces it to move to suspended state.
It also causes a thread to release its acquired lock.So that, other threads can get turn in order to perform their respective jobs.
A wait method always pair with a notify method. Both together provides a way of interthread communication.
Java program to demonstrate working of wait method ?
Program:
class WaitExample extends Thread { @Override public void run() { print(); } synchronized void print() { System.out.println("THis is child "); notify(); } } public class Main { public static void main(String[] args) { WaitExample thread = new WaitExample(); thread.start(); synchronized (thread) { System.out.println("I am in synchronised :"); try { thread.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("I am in invoked :"); }
Output:
sleep() Method
Sleep method puts a thread to sleep too but for specified milliseconds.
It allows a thread to carry out its remaining task once provided time ends. Unlike wait(), it doesn’t order a thread to release its locks until it completes its task.
Java program to demonstrate working of sleep method ?
Program:
class ThreadExample extends Thread{ @Override public void run() { System.out.println("Child thread is about to sleep"); try { sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("I am child Thread "); } } public class Main { public static void main(String[] args) { ThreadExample thread1 = new ThreadExample(); thread1.start(); System.out.println("I am Main Thread "); } }
Output
Child thread is about to sleep
I am Main Thread
I am child Thread