The major difference between yield and sleep in
Java is that yield() method pauses the currently executing thread temporarily
for giving a chance to the remaining waiting threads of the same priority to
execute. If there is no waiting thread or all the waiting threads have a lower
priority then the same thread will continue its execution. The yielded thread
when it will get the chance for execution is decided by the thread scheduler
whose behavior is vendor dependent. Yield method doesn’t guarantee that current thread will pause or stop but it
guarantee that CPU will be relinquished by current Thread as a result of a call
to Thread.yield() method in java.
1) Thread.sleep() method is used to pause the
execution, relinquish the CPU and return it to thread scheduler.
2) Thread.sleep() method is a static method and
always puts the current thread to sleep.
3) Java has two variants of sleep method in
Thread class one with one argument which takes milliseconds as the duration of
sleep and another method with two arguments one is millisecond and other is the
nanosecond.
4) Unlike wait() method in Java, sleep() method
of Thread class doesn't relinquish the lock it has acquired.
5) sleep() method throws Interrupted Exception
if another thread interrupts a sleeping thread in java.
6) With sleep() in Java it's not guaranteed
that when sleeping thread woke up it will definitely get CPU, instead it will
go to Runnable state and fight for CPU with other thread.
No comments:
Post a Comment