Thread.yield() Method in Java
The Thread.yield() method is a static method that tells the scheduler the current thread is willing to give up the CPU so other runnable threads can have a turn. The thread stays RUNNABLE and may be chosen to run again immediately. Like priorities, yield is only a hint: the scheduler may ignore it completely. It is rarely used in application code. In this lesson, you will learn what yield does, how it differs from sleep, and what to use instead.
Declaration
public static void yield()yield() vs sleep()
Thread.yield() | Thread.sleep(ms) | |
|---|---|---|
| Effect | Offers the CPU to other runnable threads | Pauses for at least the given time |
| State afterwards | Stays RUNNABLE | TIMED_WAITING |
| Guaranteed to pause | No; may continue immediately | Yes |
Throws InterruptedException | No | Yes |
| Typical use | Rare: busy-wait loops, testing | Waiting for a time |
Example: A Polite Busy Loop
Let's see an example where one thread waits for a flag set by another, yielding while it waits.
public class YieldDemo {
static volatile boolean ready = false;
public static void main(String[] args) throws InterruptedException {
Thread waiter = new Thread(() -> {
long spins = 0;
while (!ready) {
spins++;
Thread.yield();
}
System.out.println("Advitha saw the flag after spinning: "
+ (spins > 0));
});
waiter.start();
Thread.sleep(100);
ready = true;
waiter.join();
System.out.println("Done");
}
}Advitha saw the flag after spinning: true
DoneExplanation: The waiter checks the ready flag in a loop. Calling yield() on each pass lets other threads run instead of the loop hogging a core. The flag is volatile so the waiter sees the change (explained in "Volatile Keyword in Java"). Even so, this loop burns CPU for 100 milliseconds.
Better Ways to Wait
Common Mistakes
Using yield to control the order of threads. It guarantees nothing.
Expecting yield to release a lock. It doesn't.
Practice
- Easy: Explain in one sentence each how
yield,sleepandjoindiffer. - Harder: Rewrite
YieldDemoso the waiter usesjoinon a second thread instead of a flag, and compare CPU use.
Key Takeaways
Was this tutorial helpful?