Read Also : LifeCycle of Thread in Java
Difference between Yield and Sleep method in Java with Example
1. Currently executing thread state : Sleep method causes the currently executing thread to sleep for the number of milliseconds or the nanoseconds specified in the argument.
There are two overloaded sleep methods
sleep (long milliseconds) , takes milliseconds as an argument.
sleep (long milliseconds , int nanoseconds) specifies milliseconds and nanoseconds as an argument.
According to Oracle docs,
Yield method temporarily pauses the currently executing thread to give a chance to the remaining waiting threads of the same priority to execute.
If there is no waiting thread or all the waiting threads of low priority then the current thread will continue its execution.
2. Interrupted Exception : Sleep method throws the Interrupted exception if another thread
interrupts the sleeping thread . yield method does not throw Interrupted Exception.
3. Give up monitors : Thread.sleep() method does not cause cause currently executing thread to give up any monitors while yield() method give up the monitors.
Similarities between Yield and Sleep method
1. Static method : Both yield and sleep method are static method . Hence , they always change the state of currently executing thread .
2. java.lang.Thread : Both yield and sleep method belongs to the java.lang.Thread class.
3. Currently executing thread : Both methods affect the state of currently executing thread .yield method may pause it while sleep method will stop it for a specified time .
Example of Sleep and Yield method in Java
main is sleeping for 3 Seconds Main Thread had enough sleep
Yield Example Starts
I am Producer : Producing Item 0 I am Producer : Producing Item 1 I am Producer : Producing Item 2 I am Consumer : Consuming Item 0 I am Consumer : Consuming Item 1 I am Consumer : Consuming Item 2
Recap : Difference between Sleep and Yield Method in Java
|Currently Executing Thread State||Stops for the specified time||Pauses the current thread|
|Interrupted Exception||Yes , throws IE||No|
|Give Up Monitors||No||Yes|
In case you have any other query regarding difference between sleep and yield method with Example in java, then please mention in the comments .