Thread.Sleep ()
- The current thread changes state from Running to waiting/blocked as shown in the diagram below.
- Any and thread with reference to the thread currently sleeping (say T) can interrupt it calling
t.interrupt()
- The call to sleep have to is encapsulated to catch the checked exception of
InterruptedException
- After the time period for which the thread is set to sleep it goes to the Runnable state andmight not run immediately ! It has a to-wait for the Thread Scheduler to schedule it time slice.
Thread.yield ()
- Calling it may cause the thread Scheduler to move the current Thread from Running toRunnable St Ate and execute another same priority thread which is in Runnable state. This transition of the state takes place only if there are some other thread of the same priority in Runnable state. Hence the no guarantee that the thread would stop execution as the criteria of another same priority thread might Not being met.
.yield() is much based on the Thread priorities concept. (All thread was assigned priorities and when a thread of higher priority was in the Runnable state it ususally preempts/stops Execution of lower priority threads depending on implementation of ThreadScheduler.)
Note:
- Both and is
Thread.sleep() Thread.yield() static functions and affect the current thread executing it.
- Both the functions won't let go to the synchronized locks they hold.
|
Thread.Sleep () vs Thread.yield ()