Difference Between wait(), sleep() and yield() in Java

Category: Java   Tags: Java, Java Thread, Java MultiThread, Thread Synchronization

Difference between wait and sleep in Java

1.
wait()
Called from a synchronized context only. IllegalMonitorStateException exception will be thrown if not called from a synchronized context.

sleep()
Can be called without a synchronized context. It is called on a currently executing thread.
2.
wait()
It will release the lock and allow other objects to execute.

sleep()
It will keep the lock for at least specified number of milliseconds or somebody interrupt.
3.
wait()
Can be awake by calling notify and notifyAll.

sleep()
Awake after specified time expire or call interrupt().

Difference between yield and sleep in Java

1.
yield()
The yield() method pauses the currently executing thread temporarily and allow remaining waiting threads of the same priority to execute.

In case if there is no waiting thread or all the waiting threads have a lower priority, current thread will continue its execution.

It is thread scheduler that decide when the yielded thread should be executed.


sleep()
It causes the currently executing thread to sleep for the specified number of time.