首页 > 文章列表 > yield()方法在Java中的重要性是什么?

yield()方法在Java中的重要性是什么?

java 重要性 关键词:yield方法
280 2023-08-26

yield()方法是Thread类的静态方法,它可以停止当前正在执行的线程线程,并将给相同优先级的其他等待线程一个机会。 如果没有等待线程或者所有等待线程都低优先级,则同一个线程将继续执行。 yield()方法的优点是有机会执行其他等待线程,因此如果我们当前线程需要更多时间来执行并将处理器分配给其他线程。

语法

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();
      thread.start();
      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