Sunday, November 13, 2016

Difference between Sleep and Wait

sleep() is a method which is used to hold the process for some time but wait() method causes the thread to go in waiting state and it won’t come back automatically until notify() or notifyAll() is called.

The major difference is that wait() releases the lock while sleep() does not release any lock.

Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread.
Even if we call t.sleep() where t is a different thread; even then, the current thread will sleep, not the t thread.

object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the lock object. Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread.

No comments:

Post a Comment

Home