Java 中yield()方法的重要性?
javaobject oriented programmingprogramming更新于 2024/7/26 3:08:00
yield()方法是Thread类的静态方法,它可以停止当前正在执行的线程,并为其他等待的相同优先级的线程提供机会。如果没有等待线程,或者所有等待线程的优先级都较低,则同一线程将继续执行。yield()方法的优点是有机会执行其他等待线程,因此如果我们的当前线程需要更多时间执行并将处理器分配给其他线程。
语法
public static void Yield()
示例
class MyThread extends Thread { public void run() { for (int i = 0; i < 5; ++i) { Thread.yield(); // 通过调用此方法,MyThread 停止其执行并将机会交给主线程 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