Differences and similarities between yield() and sleep() in java in threads



Differences yield() and sleep() :

  • Definition : yield() method when called on thread gives a hint to the thread scheduler that the current thread is willing to yield its current use of a processor. The thread scheduler is free to ignore this hint. sleep() methods causes current thread to sleep for specified number of milliseconds (i.e. time passed in sleep method as parameter). Ex- Thread.sleep(10) causes currently executing thread to sleep for 10 millisec.

  • Thread state : when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up. when yield() method is called on thread it goes from running to runnable state, not in waiting state. Thread is eligible to run but not running and could be picked by scheduler at anytime.

  • Exception : yield() method doesn’t throws any exception. But sleep() method throws compile time exception i.e. InterruptedException.

  • Waiting time : yield() method stops thread for unpredictable time, that depends on thread scheduler. But sleep() method have got few options.
    1. sleep(long millis) - Causes the currently executing thread to sleep for the specified number of milliseconds
    2. sleep(long millis, int nanos) - Causes the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.


similarity between yield() and sleep():

> yield() and sleep() method belongs to java.lang.Thread class.

> yield() and sleep() method can be called from outside synchronized block.

> yield() and sleep() method are called on Threads not objects.


/** JavaMadeSoEasy.com */

RELATED LINKS>


Differences between important thread methods >

Difference between wait() and sleep() method in threads

Differences and similarities between yield() and sleep() in threads

Difference between notify() and notifyAll() methods, with program

Difference between wait() and wait(long timeout) -What will be Thread states




Interviews >

THREADS - Top 75 interview questions and answers (detailed explanation with programs) Set-1 >  Q1- Q54

THREADS - Top 75 interview questions and answers, important interview OUTPUT questions and answers, Set-2 > Q55- Q76





Must read for you :

No comments:

Post a Comment