I know one difference:
If we say thread.sleep(1000)
, that thread will sleep for 1000
milliseconds for sure, whereas with yield()
yield() pauses momentarily the current thread, allowing the Thread Scheduler to execute other threads with the same priority. If there are no other threads waiting or their priority is lower, the yielded thread returns to its execution at once.
sleep() forces the current thread to halt its execution for a defined slot of time. Other waiting threads will start executing by taking advantage of this pause, that is, following the Thread Scheduler policy - whose implementation is vendor dependent.
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.
yield
merely says: now is a good time to let another thread run and is a hint to the scheduler. sleep
really does that: sleep at least the given time.
t.interrupt()
InterruptedException
.yield()
is much based on the Thread Priorities concept. (All thread are assigned priorities and when a thread of higher priority is in Runnable state it ususally preempts / stops execution of lower priority threads depending on implementation of ThreadScheduler.)Note:
Thread.sleep()
and Thread.yield()
are static functions and affect the current thread executing it.