Interview Questions

Differences and similarities between yield() and sleep() ?

Java Interview Questions and Answers (part 4)


(Continued from previous question...)

31. Differences and similarities between yield() and sleep() ?

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 need not to catch or throw any exception. But sleep() method must catch or throw 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.
sleep(long millis) - Causes the currently executing thread to sleep for the specified number of milliseconds
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.

(Continued on next question...)

Other Interview Questions