9

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?

Community
  • 1
  • 1
Hesey
  • 4,957
  • 6
  • 31
  • 31
  • 1
    As these method are very implementation dependant it is very hard to say. You should not rely on the behavour of these methods. for example if you have a loop which just does Thread.yield() it won't give up the CPU 99%+ of the time. Thread.sleep(0) may sleep from 0.5 to 2 ms depending on the OS, giving up the CPU, but this is not guarenteed either. – Peter Lawrey Jan 28 '11 at 11:32

2 Answers2

5

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)

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
-3

Thread.sleep() will just pause the thread and not give away control. Thread.yield() will pause the thread and allow other threads to run. If no threads need to, the original thread will resume immediately.

mrbellek
  • 2,300
  • 16
  • 20
  • 3
    Wrong, I think. Thread.sleep() will take the Thread out of the Running state, and allow the scheduler to switch another Runnable Thread to Running (as will Thread.yield()). The Thread does, however, keep any locks it holds. – Highland Mark Jan 28 '11 at 12:05