Java Yield Keyword Explained

In Java, the usage of the yield keyword differs from other programming languages like Python. In Java, the yield keyword is primarily used to control the execution of multiple threads.

The purpose of the yield keyword is to pause the execution of the current thread, allowing other threads a chance to continue. When a thread calls the yield method, it is placed in a waiting queue, waiting for the scheduler to reschedule it. If there are no other threads available to execute, then the current thread will continue its execution.

Using the yield keyword enables collaboration and coordination between threads. By yielding the CPU execution, the efficiency of multi-threaded programs can be improved.

Here is an example of using the yield keyword:

public class YieldExample implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
            Thread.yield();
        }
    }

    public static void main(String[] args) {
        YieldExample example = new YieldExample();
        Thread t1 = new Thread(example);
        Thread t2 = new Thread(example);

        t1.start();
        t2.start();
    }
}

In the above example, we created two threads (t1 and t2) that share the same YieldExample instance. In the run method of YieldExample, we use the yield keyword to pause the current thread’s execution and allow other threads to run. This way, the t1 and t2 threads will take turns running, with each thread printing 5 times.

bannerAds