This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I want to know when we apply Thread.yield() on a running thread ,what actually happen.it goes to runnable state and come back again to running state or goes to runnable and never come back or nothing happens.please clarify my confusion.
yield() causes the currently executing thread object to temporarily pause and allow other threads with the same to execute. But yield() method is also dependent on the process scheduling algorithm of the OS, so , in other words, don�t try to use yield() and use sleep() method instead.
don�t try to use yield() and use sleep() method instead
I think yield and sleep are intended for different situations. yield is used to give other threads precedence. If currently no other threads are running (maybe they sleep or wait), then yield has no effect, while sleep always causes your thread to leave the running state.
Originally posted by Ashok Pradhan: I want to know when we apply Thread.yield() on a running thread ,what actually happen.it goes to runnable state and come back again to running state or goes to runnable and never come back or nothing happens.please clarify my confusion.
Using yield() causes a thread to go into runnable state and allows other threads to execute while pausing the current thread. However, this is in no way guaranteed since the scheduling is OS dependent and the scheduler may decide to give time to this very thread again. It is therefore recommended that if you _absolutely_ need a thread to go out of execution, you should use sleep() instead of yield().
As to the second point, the thread will come back again for execution if you use yield().
Joined: Jun 05, 2008
I didn't say that yield() and sleep() methods are the same. If you want the current running thread leave the running state and let other threads execute, use sleep() method instead of yield() because yield() method can have no effect.