What is the difference between sleep and yield method in java?

Lets look at the difference between the sleep and wait method :

sleep method :

sleep is the static method in Thread class. This method temporarily ceases the execution of the executing thread for specified milliseconds. In sleep method we can also pass the nano seconds along with milliseconds to pause a thread.
When we call sleep on thread, that thread keeps monitors which it has acquired. So if the thread is inside a synchronized method or block then no other thread can enter inside it but if another thread calls interrupt on this thread then this thread wakes up. sleep method throws interrupted exception.

wait method :

wait is a non static method in Object class. wait method allows other thread to run by releasing a lock it holding on an object. wait method comes with the constructors as shown below :

public final void wait()
public final void wait(long timeout) // timeout is in milliseconds
public final void wait(long timeout, int nanos) //finer control on the time specified for wait (timeout * 1000 + nanoseconds)

wait method is instance specific, i.e. it is called by a thread object. wait can only be invoked from the synchronized code.
Thread keep itself in wait state until
1. Another thread calls notify on this object and scheduler chooses to run this thread.
2. Another thread calls notifyAll.
3. wait time elapses.
4. Another thread interrupts the thread on which wait is called.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment


Post a Comment