JavaGian java tutorial and java interview question and answer

JavaGian , Free Online Tutorials, JavaGian provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, ajax, core java, sql, python, php, c language etc. for beginners and professionals.

Sleep vs yield in Java


Sleep vs yield in Java

Sleep and yield are two methods which are used to get CPU back from Thread to Thread Scheduler in java but they are completely different than each other. The major difference between Sleep vs yield is that sleep is more reliable than yield and it's advised to use sleep(1) instead of yield to relinquish CPU in multi-threaded Java application to give an opportunity to other threads to execute. In this Java tutorial, we will what are differences between yield and sleep in Java. But before seeing difference between sleep and Yield let's see some similarities between yield and sleep in Java



Similarities between Sleep and yield in Java

 Here are some common things between sleep and yield method in Java programming :

1) Both yield and sleep are declared on java.lang.Thread class.

2) Both sleep() and yield() are static methods and operate on current thread. It doesn't matter which thread's object you used to call this method, both these methods will always operate on current thread.

3) Sleep as well as Yield is used to relinquish CPU from current thread, but at same time it doesn't release any lock held by the thread. If you also want to release locks along with releasing CPU, you should be using wait() method instead. See difference between sleep() and wait() method for more details.

Now let's see what are differences between Sleep and Yield in Java and what are best practices to use sleep and yield in Java multi-threaded program:


Difference between sleep and yield in Java

Difference between Sleep and yield in Java1) Thread.sleep() method is overloaded in Java as sleep(long milliseond) and sleep(long millis, int nanos) . former version of sleep will stop current thread for specified millisecond while later version of sleep allows to specify sleep duration till nanosecond. Thread.sleep() will cause currently executing thread to stop execution and relinquish the CPU to allow Thread scheduler ot allocate CPU to another thread or same thread depends upon Thread scheduler. Thread.yield() also used to relinquish CPU but behavior of sleep() is more determined than yield across platform. Thread.sleep(1) is better option than calling Thread.yield for same purpose.

2) Thread.sleep() method doesn't cause currently executing thread to give up any monitors while sleeping.

3) Thread.sleep() method throws InterruptedExcepiton if another thread interrupt the sleeping thread, this is not the case with yiedl method.

.