File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion on yield() method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusion on yield() method?" Watch "Confusion on yield() method?" New topic
Author

Confusion on yield() method?

Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

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.
Antonio Tercero
Ranch Hand

Joined: Jun 05, 2008
Posts: 110
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.


SCJP 5, SCWCD 5
Ralph Jaus
Ranch Hand

Joined: Apr 27, 2008
Posts: 342
Antonio wrote
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.


SCJP 5 (98%) - SCBCD 5 (98%)
Gaurav Arora
Ranch Hand

Joined: Aug 13, 2007
Posts: 35
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().
Antonio Tercero
Ranch Hand

Joined: Jun 05, 2008
Posts: 110
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusion on yield() method?