I know one difference:
If we say thread.sleep(1000)
, that thread will sleep for 1000
milliseconds for sure, whereas with yield()
It's not "for sure" -- it could even take an hour for your thread to get another chance to run, depending on the operating system's thread scheduling algorithm, and the presence of higher-priority threads.
The only thing yield()
does is say, "Okay, I'm kind of done, so feel free to end my time slice and continue executing something else." sleep
, on the other hand, says "Wake me up in X milliseconds". sleep
is used for waiting, the other one for giving others a chance to run. They're not alternatives.