yield() 方法在 Java 中的重要性是什么?
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:Thread-0 Thread started:Thread-0 Thread started:Thread-0 Thread started:Thread-0 Thread started:Thread-0 Thread started:main Thread ended:Thread-0 Thread started:main Thread started:main Thread started:main Thread started:main Thread ended:main
广告