Amazon Interview Question
Software Engineer / DevelopersSleep Method puts thread to waiting state of the process life cycle. Once the thread has slept or waited in the waiting queue for specified amount of time it eneters the Runnable state to get executed.
Whereas by yielding a Thread goes into Runnable state leaving the running state to get executed.
Also one more difference is , that if thread is running in the synchronized mode and then it goes to sleep mode it still holds the lock. However in the case of yield in the synchronized mode, the thread that is yielding has to release the lock. And therefore another thread can acquire the lock on that object
sleep(t) make the current executing thread to sleep for 't' mill seconds. No matter what it will sleep for 't' milliseconds.
- master January 03, 2010yield() make the current thread to temporarily pause and allows other thread to run. The thread which gets executed dependents on individual threads priority too. Current thread goes into runnable state and place itself in ready queue.
The difference here is that....
if when sleep is called current thread will go to sleep and other runnable thread will take over the processing if there are any. If there are no runnable thread then nothing happens current thread will continue to sleep for 't'.
But in case of yield() current thread give the control to other runnable threads, but if there are none, it takes the control immediately.