Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusion on yield() method?

 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ralph Jaus
Ranch Hand
Posts: 342
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gaurav Arora
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic