What is difference between sleep(), yield() and wait() method?

By | August 12, 2019

In this blog post we will discuss about one of the very important java interview question  What is difference between sleep(), yield() and wait() method? 

  • wait() method releases the acquired lock when the thread is waiting till some other thread calls notify() while Thread. sleep(sleepTime) method keeps the lock even if thread is waiting

 

  • wait() can only be called from synchronized context otherwise it will throw IllegalMonitorStateException, while sleep(sleepTime) can be called from any code block.
  • wait() is called on an Object while sleep(sleepTime) is called on a Thread
  • waiting thread can be awaken by calling notify()/notifyAll() methods while sleeping thread can’t be awaken (though can be interrupted)
  • Incase of sleep(sleepTime) Thread immediately goes to Runnable state after waking up while in case of wait(), waiting thread first fights back for the lock and then go to Runnable state.
  • The main 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 current thread will continue its execution.

You may also like:

What are common multi-threading issues faced by Java Developers?
What happens when wait() & notify() methods are called?
What are different states of a Thread? What does those states tell us?
What is difference between Callable and Runnable Interface?
What is difference between intrinsic synchronization and explicit locking using Lock?
What will happen when an exception arises from within a synchronized code block? Will lock be retained or released?
What is difference between Executor submit() and execute() method?

That’s all about  What is the difference between sleep(), yield() and wait() method?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *