Tuesday 31 January 2012

Thread.yield() in Java Thread

The Thread.yield() method is essentially used to notify the system that the current thread is willing to "give up the CPU" for a while. The thread scheduler may select another runnable thread with the same or greater priority to run instead of the current thread.

What yield() is supposed to do is make the currently running thread move back to runnable to allow other threads of the same priority(and those of greater priority) to get their turn.

So the intention to use yield() is that equally distribute the CPU time among equal-priority threads.But there is no guarantee for that ,because the yielding thread itself may be selected to run again.i.e the yielding thread is eligible to compete with other equal-priority threads for CPU time.

A yield() won't ever cause a thread to go to the waiting/sleeping/ blocking
state. At most, a yield() will cause a thread to go from running to runnable, but
again, it might have no effect at all.


When to use yield()?

I would say practically never. The yield method's behavior isn't standardly defined and there are generally better ways to perform the tasks that you might want to perform with yield().We have four methods sleep,join ,wait and notify to replace yield method in a better way.

The links that may help you


join method in java with example
Thread.sleep method in java with example
wait(),notify() and notifyAll() in java with example

No comments:

Post a Comment