views:

797

answers:

5

Are these two statement equivalent?

Thread.sleep(0);
Thread.yield();
+11  A: 

Yield adds the current thread to the ready queue and allows other threads to run. Sleep is not guaranteed to relinquish the cpu.

yx
I think it's really more platform-dependent than that. See my post below.
Neil Coffey
+6  A: 

yield() tells the JVM Thread Scheduler that it's OK to give other threads time slices. Usually the JVM uses this call to activate another thread of the same thread priority. In a good preemptive multithreading environment, yield() is a no-op. However, it is important in a cooperative multithreading environment, since without yield(), one thread can eat up all of the CPU.

sleep(x) tells the JVM Thread Scheduler to actively put this thread to sleep and not run it again until at least x milliseconds have elapsed.

Neither sleep() nor yield() change anything about the status of synchronization locks. If your thread has a lock, and you call sleep(1000), then at least a second will elapse before your thread wakes up. When it wakes up it may decide to release the lock -- or it may hold on to it longer.

SOURCE: http://www.jguru.com/faq/view.jsp?EID=425624

Roberto Aloi
+7  A: 

No. The most obvious difference is that sleep() throws the (checked) InterruptedException. In practice, the effect may be almost the same, but it's entirely implementation-dependant.

I'd wager that doing each a million times in a row would take much longer for sleep(), since system timer granularity probably often causes it to actually sleep for a non-negligible amount of time.

Michael Borgwardt
that's a good point, something like sleep(1) may take much longer than 1 millisecond due to granularity.
yx
+2  A: 

Thread.Yield can give up CPU resource to threads with lower priorities, while Thread.Sleep(0) gives up CPU only to threads with equal or higher priorities.

At least on Windows platform :)

Vitaliy Liptchinsky
+4  A: 

This really depends on the platform and version of the JVM. For example, under Windows in JDK 5 (Hotspot), yield() is literally implemented as Sleep(0)-- although a sleep of 0 is treated slightly specially by Windows as I recall. But in JDK 6, yield() is implemented as SwitchToThread().

I put together some information a while ago on Thread.yield(), including some implementational details that may be of interest. (You might also want to see the stuff on Thread.sleep() I put together on the same site.)

Neil Coffey