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
廣告