In this section we are going to describe yield() method with example in java thread.
In this section we are going to describe yield() method with example in java thread.In this section we are going to describe yield() method with example in java thread.
yield() Method:
When you want to stop current thread and switch the CPU availability to another thread, call yield() method of Thread.
public static void yield() - This method pauses the
execution of current running thread and permits the other threads to execute.
Example :This example represents the functionality of yield() method.
public class ThreadYield implements Runnable { Thread thread; public ThreadYield(String name) { thread = new Thread(this, name); thread.start(); } public void run() { System.out.println(Thread.currentThread().getName() + " is going to call yield() method..."); Thread.yield(); System.out.println(Thread.currentThread().getName() + " is completed."); } public static void main(String[] args) { new ThreadYield("Thread 1"); new ThreadYield("Thread 2"); } }
Output :
Thread 1 is going to call yield() method... Thread 2 is going to call yield() method... Thread 1 is completed. Thread 2 is completed.