Difference Between sleep and yield Method in Java
In java if a thread doesn’t want to perform any operation for a particular amount of time then we should go for the sleep() method, which causes the currently executing thread to stop for the specified number of milliseconds.
public static native void sleep( long ms) throws InterruptedException ; // The above method put the thread in sleep for a specified number of millisecond
public static void sleep(long ms , int ns) throws InterruptedException // The above method also put the thread in sleep for a specified number of milliseconds // plus specified number of nanoseconds
Method 1: sleep() method
Every sleep() method in java throws an InterruptedException which is a checked exception hence whenever we are using the sleep method compulsory we should handle it either by try-catch or by throws keyword otherwise we will get compile-time error.
Implementation: Here, we put the main thread in sleep for 5second after the “println” statement. So every slide takes 5second to print.
Note: Here slide-1 will be printed after slide-0 after 5000 nanoseconds so do apply for the rest of all the slides. Hence this output will be displayed taking a certain time in execution in the runtime state.
Method 2: yield() method
It causes to pause the currently executing thread to give the chance for waiting thread of same priority. If there are no waiting threads or all waiting threads have low priority then the same thread can continue its execution. If multiples thread is waiting with same priority then which waiting thread will get the chance we can’t say it depends on the thread scheduler. The thread which is yield when it will get the chance once again also depends on the thread scheduler.
public static native void yield( );
In the above program if we are commenting the line Thread.yield() both threads will be executed simultaneously, and we can’t expect which thread will get completed first. If we are not commenting Thread.yield() method then because of that main thread will get a chance more times and the chance of completing the main thread first is high.
So finally we are done with both the methods, let s finally conclude the differences between them.
Property Yield Method Sleep Method Purpose If a thread wants to pause its execution to give chance for the remaining thread of the same priority then we should go for the yield method. If a thread doesn’t want to perform any operation for a particular amount of time then we should go for the sleep method Over-loading This method is not overloaded The sleep method is overloaded. Exception This method doesn’t throw an exception This method throws Interrupted Exception Native This method is native Amongst the two overloaded methods, only sleep(long ms) is overloaded while the other is not. Give up monitors This method gives up the monitors. This method doesn’t cause the currently executing thread to give up monitors.