Home >Java >javaTutorial >What is the importance of yield() method in Java?

What is the importance of yield() method in Java?

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2023-09-07 21:05:021472browse

What is the importance of yield() method in Java?

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.

Syntax

public static void yield()

Example

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());
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete