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(); <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()); } }
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
以上是yield()方法在Java中的重要性是什麼?的詳細內容。更多資訊請關注PHP中文網其他相關文章!