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?

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

Leave a Reply

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