Thread.yield() Method in Java

Naveen AnamaneniUpdated · 3 min read

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

Declaration
public static void yield()

yield() vs sleep()

Thread.yield()Thread.sleep(ms)
EffectOffers the CPU to other runnable threadsPauses for at least the given time
State afterwardsStays RUNNABLETIMED_WAITING
Guaranteed to pauseNo; may continue immediatelyYes
Throws InterruptedExceptionNoYes
Typical useRare: busy-wait loops, testingWaiting 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.

YieldDemo.java▶ Try it
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");
    }
}
Output
Advitha saw the flag after spinning: true
Done

Explanation: 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

  1. Easy: Explain in one sentence each how yield, sleep and join differ.
  2. Harder: Rewrite YieldDemo so the waiter uses join on a second thread instead of a flag, and compare CPU use.

Quick check: yield()

4 questions
1What does Thread.yield() do?
2What state is a thread in after yield()?
3Does yield() release locks?
4What should replace busy-waiting with yield?

Key Takeaways

Was this tutorial helpful?

Lesson 390 of 482