Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Thread.yield() and Thread.sleep() [duplicate]

Can someone explain the difference between Thread.yield() method and Thread.sleep() method?

How I understand it: Thread.yield() gives up the monitor lock to other thread which JVM decides to execute next, and Thread.sleep() puts the current thread in sleep mode for a given amount of milliseconds without giving away the monitor lock.

like image 375
ASingh Avatar asked Apr 14 '26 14:04

ASingh


1 Answers

It depends on what Java version you are using, according to this:

In Java 5, Thread.yield() calls the Windows API Sleep(0). This has the special effect of clearing the current thread's quantum (number of allocated time-slices of CPU) and putting it to the end of the queue for its priority level. In other words, all runnable threads of the same priority (and those of greater priority) will get a chance to run before the yielded thread is next given CPU time. When it is eventually re-scheduled, it will come back with a full quantum, but doesn't "carry over" any of the remaining quantum from the time of yielding. This behavior is a little different from a non-zero sleep where the sleeping thread generally loses 1 quantum value (in effect, 1/3 of a 10 or 15ms tick).

In Java 6, this behavior was changed. The Hotspot VM now implements Thread.yield() using the Windows SwitchToThread() API call. This call makes the current thread give up its current time-slice, but not its entire quantum. This means that depending on the priorities of other threads, the yielding thread can be scheduled back in one interrupt period later.


Thread.sleep() suspends the current thread for a specified time, no matter what Java version you use.

like image 171
syb0rg Avatar answered Apr 16 '26 03:04

syb0rg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!