yield() method is a static method of the Thread class, which can stop the current execution thread and will give other waiting threads of the same priority a chance. If there are no waiting threads or all waiting threads are low priority, the same thread will continue to execute. yield() The advantage of the method is that there is a chance to execute other waiting threads, so if our current thread needs more time to execute and assign the processor to other threads.
public static void yield()
class MyThread extends Thread { public void run() { for (int i = 0; i < 5; ++i) { Thread.yield(); // By calling this method, MyThread stop its execution and giving a chance to a main thread System.out.println("Thread started:" + Thread.currentThread().getName()); } System.out.println("Thread ended:" + Thread.currentThread().getName()); } } public class YieldMethodTest { public static void main(String[] args) { MyThread thread = new MyThread(); <strong> </strong>thread.start();<strong> </strong> for (int i = 0; i < 5; ++i) { System.out.println("Thread started:" + Thread.currentThread().getName()); } System.out.println("Thread ended:" + Thread.currentThread().getName()); } }
Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread started:main Thread started:Thread-0 Thread ended:main Thread ended:Thread-0
The above is the detailed content of What is the importance of yield() method in Java?. For more information, please follow other related articles on the PHP Chinese website!