The difference between wait and sleep or the difference between sleep and yield in Java is one of the popular core Java interview questions and asked on multi-threading interviews. Out of three methods that can be used to pause a thread in Java, sleep() and yield() methods are defined in thread class while wait() is defined in the Object class, which is another interview question. The key difference between wait() and sleep() is that the former is used for inter-thread communication while later is used to introduced to pause the current thread for a short duration. This difference is more obvious from the fact that, when a thread calls the wait() method, it releases the monitor or lock it was holding on that object, but when a thread calls the sleep() method, it never releases the monitor even if it is holding.
Coming back to yield(), it's little different than wait() and sleep(), it just releases the CPU hold by Thread to give another thread an opportunity to run though it's not guaranteed who will get the CPU.
It totally depends upon thread scheduler and it's even possible that the thread which calls the yield() method gets the CPU again. Hence, it's not reliable to depend upon the yield() method, it's just on the best effort basis.
Coming back to yield(), it's little different than wait() and sleep(), it just releases the CPU hold by Thread to give another thread an opportunity to run though it's not guaranteed who will get the CPU.
It totally depends upon thread scheduler and it's even possible that the thread which calls the yield() method gets the CPU again. Hence, it's not reliable to depend upon the yield() method, it's just on the best effort basis.
Wait vs Sleep vs Yield in Java
In this Java tutorial, we will learn what is sleep in Java, important points of sleep in java and the difference between Wait and sleep in Java.Difference between Wait and Sleep in Java
The main difference between wait and sleep is that wait() method releases the acquired monitor when the thread is waiting while Thread.sleep() method keeps the lock or monitor even if the thread is waiting. Also, wait for the method in Java should be called from a synchronized method or block while there is no such requirement for sleep() method.
Another difference is Thread.sleep() method is a static method and applies on the current thread, while wait() is an instance-specific method and only got wake up if some other thread calls notify method on the same object.
Also, in the case of sleep, sleeping thread immediately goes to Runnable state after waking up while in the case of wait, waiting for a thread first acquires the lock and then goes into Runnable state. So based upon your need, if you want to pause a thread for a specified duration then use the sleep() method, and if you want to implement inter-thread communication use the wait method.
And, if you like to see differences in tabular format for better understanding, here is a nice table which which highlights all differences between wait(), sleep(), and yield() method in Java:
Another difference is Thread.sleep() method is a static method and applies on the current thread, while wait() is an instance-specific method and only got wake up if some other thread calls notify method on the same object.
Also, in the case of sleep, sleeping thread immediately goes to Runnable state after waking up while in the case of wait, waiting for a thread first acquires the lock and then goes into Runnable state. So based upon your need, if you want to pause a thread for a specified duration then use the sleep() method, and if you want to implement inter-thread communication use the wait method.
Here is the list of difference between wait and sleep in Java :
1) wait is called from synchronized context only while sleep can be called without synchronized block. see Why to wait and notify needs to call from the synchronized method for more detail.
2) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awakened by calling notify method.
3) wait is normally done on the condition, Thread waits until a condition is true while sleep is just to put your thread on sleep.
1) wait is called from synchronized context only while sleep can be called without synchronized block. see Why to wait and notify needs to call from the synchronized method for more detail.
2) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awakened by calling notify method.
3) wait is normally done on the condition, Thread waits until a condition is true while sleep is just to put your thread on sleep.
4) wait for release lock on an object while waiting while sleep doesn’t release the lock while waiting.
5) The wait() method is called on an object on which the synchronized block is locked, while sleep is called on the Thread. See these Java Multithreading courses for more details on how to use wait() and notify method in Java.
5) The wait() method is called on an object on which the synchronized block is locked, while sleep is called on the Thread. See these Java Multithreading courses for more details on how to use wait() and notify method in Java.
Difference between yield and sleep in Java
The major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution.
The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee that the current thread will pause or stop but it guarantees that CPU will be relinquished by current Thread as a result of a call to Thread.yield() method in java. See Java Concurrency in Practice for more details.
The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee that the current thread will pause or stop but it guarantees that CPU will be relinquished by current Thread as a result of a call to Thread.yield() method in java. See Java Concurrency in Practice for more details.
Sleep method in Java has two variants one which takes millisecond as sleeping time while others which takes both mill and nanosecond for the sleeping duration.
sleep(long millis)
or
sleep(long millis,int nanos)
Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.
Here is nice diagram which shows how thread transition happen to different thread states by calling the wait(), sleep() and yield() methods.
Example of Thread.sleep() method in Java
Here is a sample code example of Sleep Thread in Java. In this example, we have put the Main thread in Sleep for 1 second.
/*
* Example of Thread Sleep method in Java
*/
public class SleepTest {
public static void main(String... args){
System.out.println(Thread.currentThread().getName() + " is going to sleep for 1 Second");
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Main Thread is woken now");
}
}
Output:
main is going to sleep for 1 Second
Main Thread is woken now
10 points about Thread sleep() method in Java
I have listed down some important and worth to remember points about Sleep() method of Thread Class in Java:
1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.
3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as the duration of sleep and another method with two arguments one is millisecond and other is the nanosecond.
4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.
5) sleep() method throws Interrupted Exception if another thread interrupts a sleeping thread in java.
6) With sleep() in Java it's not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.
7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put the current thread into Sleeping state and not thread "t".
That’s all on Sleep method in Java. We have seen the difference between sleep and wait along with sleep and yield in Java. In Summary, just keep in mind that both sleep() and yield() operate on the current thread.
Java Tutorial you may like:
Moreover, developers can look at the java source for these methods to get more insight into java multithreading tutorial
ReplyDeleteThread.currentThread().sleep(1000);
ReplyDeleteshould be written as
Thread.sleep(1000);
since sleep is a static method
Hi @Anonymous, yes it Thread.sleep() is absolutely Ok and static method should be called like that but I still like Thread.currentThread().sleep() because its much clearer on saying that current thread is going to sleep.
ReplyDeleteDon't rely on Thread.yield method, in one JVM yield method may produce desired result but may not work on other JVM. Instead of using yield method use Thread.sleep(1) but don't use Thread.sleep(0) which will return immediately.
ReplyDeleteWhat is the state of Thread, when we call sleep(), wait() or yeild() methods? This questions was asked to me on JP Morgan Interview.
ReplyDeleteA thread can be in WAITING or TIMED_WAITING state, due to a call to wait() or sleep() method. If you call wait and sleep without timeout then Thread will be in WAITING (ThreadState.WAITING) state, while a call to sleep() and wait() without timeout will leave thread in TIMED_WAITING state. Difference between WAITING and TIMED_WAITING state is timeout, which means thread will come out once timeout is expired.
ReplyDeletei got confused in wait and sleep..please clarify more..
ReplyDeleteDoes using Thread.sleep(few minutes) puts a load on CPU?
ReplyDeleteI mean i am executing a method that consumes CPU heavily (actually it will zip a large text file) .
So, after that method i want current thread to sleep for few minutes before calling the method again to archive another file. I am doing this so that other programs can also run smoothly.
i need to execute a job like it has to run execute for one minute and other minute on idle, while it was on idle other function has to run.it works for 24/7, can you please help on this?
ReplyDeletePlease, could you explain this statement further:
ReplyDelete"... There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t" ...."
Balvinder said,
ReplyDeleteBut if the thread which executes yield is not release the lock then how it allows the other thread to execute ? Because without acquiring the lock no one thread can allowed to execute.
Please, could you explain this statement further:
ReplyDelete"... There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t" ...."
There is no use in writing t1.sleep or t2.sleep, since t1.sleep/t2.sleep always puts the current thread.sleep. i.e. Asking t2.sleep from t1's code is meaningless.
@Sarath, right way to call sleep() method is Thread.currentThread().sleep(), it's not advised to call static method on instances, even thought compiler allows it, it's not recommended because of confusion it creates.
ReplyDeleteHi,
ReplyDeleteThanks for the post. In the thread lifecylce diagram, there is an issue. From 'sleeping' state to 'ready-t-run' state transition will happen by interruption or after completion of sleep time. However, it is incorrectly written as notify.
@Anonymous, good catch. You are right a thread will go to sleeping to ready to run state after sleep duration finished or interruption.
ReplyDeletethe diagram shows the sleeping thread is wake up by "object.notify or object.notifyAll" ??? so a notify could wake up a sleep thread ?
ReplyDelete@Jason, no, if it is sleeping due to Thread.sleep() it cannot wake it up.
ReplyDeleteYou have yourself mentioned - "waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awakened by calling notify method". However your diagram says otherwise. Need to correct that. Since sleep() does not release lock - notify() or notifyAll() does not come into picture.
ReplyDelete@Aniket, the diagram is incorrect on that front, sleep() doesn't release lock hence no need to call notify or notifyall to inform other waiting threads.
ReplyDelete