首頁 > Java > java教程 > 主體

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

WBOY
發布: 2023-09-07 21:05:02
轉載
1386 人瀏覽過

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();
<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中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!