Yield method of the Thread class

Yield method of the Thread class

The yield() method of the Thread class in Java is used to hint to the scheduler that the current thread is willing to yield its current use of a processor. It does not guarantee that the processor will be yielded, but it allows the scheduler to make a decision based on the thread’s hint. Essentially, yield() suggests that the current thread is not particularly important and could give up its CPU time to allow other threads to run.

Explanation

  • When a thread calls yield(), it temporarily relinquishes the CPU and goes back to the ready state, allowing other threads of the same or higher priority to execute. However, there is no guarantee that the scheduler will honor the yield request.
  • yield() can be used in scenarios where a thread is performing a task that is not time-critical, and giving up the CPU for a short period won’t adversely affect the application’s performance.

Yield method

Example
java
public class YieldExample {
    public static void main(String[] args) {
        Runnable task = () -> {
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
                // Yield control to other threads after printing each number
                Thread.yield();
            }
        };

        Thread thread1 = new Thread(task, "Thread 1");
        Thread thread2 = new Thread(task, "Thread 2");

        thread1.start();
        thread2.start();
    }
}

Example

In this example, two threads thread1 and thread2 are created, each executing the same task. Inside the task, the threads print numbers from 1 to 5. After printing each number, Thread.yield() is called, suggesting to the scheduler that the current thread can yield the CPU. As a result, the execution of the threads may interleave, and both Yield method of the Thread class may get a chance to execute concurrently. However, the scheduler’s behavior ultimately determines the actual execution order.

Homepage

Readmore