Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Thread.yield() and Thread.sleep(0) in Java? [duplicate]

Possible Duplicate:
Are Thread.sleep(0) and Thread.yield() statements equivalent?

In my understanding, both Thread.yield() and Thread.sleep(0) should make the CPU rejudge which thread to run by some scheduling algorithm.

The difference is:

  1. Thread.yield() is to give the executive chance to other threads, but Thread.sleep(0) will not, it'll just tell CPU that you should rearrange the executive threads including the current thread itself.

  2. Thread.yield() is just an advice which means it may not be accepted at all, but Thread.sleep(0) will do the rearrangement forcedly.

Are the two above conclusions right?

like image 978
Hesey Avatar asked Jan 28 '11 10:01

Hesey


1 Answers

Thread.Sleep() has a slightly larger overhead because it creates a system that includes some kind of timer that will wake the process. (Depends on implementation basically)
Bottom line it will call a Yield() in the end.

Thread.Yield() Will just give-up the thread's turn, and gain it in the next round.

Thread.Sleep(0) might have an optimization to just call yield. (Again, implementation)

like image 111
Yochai Timmer Avatar answered Oct 14 '22 08:10

Yochai Timmer