Java 執行緒 yield() 方法



描述

Java Thread yield() 方法導致當前正在執行的執行緒物件暫時暫停,並允許其他執行緒執行。

宣告

以下是 java.lang.Thread.yield() 方法的宣告

public static void yield()

引數

返回值

此方法不返回值。

異常

示例:暫停當前正在執行的執行緒

以下示例演示了 java.lang.Thread.yield() 方法的使用。在此程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在建構函式中,我們建立了一個新執行緒並使用 start() 方法啟動它。

在 run() 方法中,我們啟動了一個 for 迴圈,在第 5 次迭代中,使用 yield() 方法暫停當前正在執行的執行緒。run() 方法結束後,會列印一條包含當前執行緒詳細資訊的訊息。在 main() 方法中,建立了三個 ThreadDemo 類的執行緒。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   Thread t;

   ThreadDemo(String str) {

      t = new Thread(this, str);
      // this will call run() function
      t.start();
   }

   public void run() {

      for (int i = 0; i < 5; i++) {
         // yields control to another thread every 5 iterations
         if ((i % 5) == 0) {
            System.out.println(Thread.currentThread().getName() + " yielding control...");

            /* causes the currently executing thread object to temporarily 
            pause and allow other threads to execute */
            Thread.yield();
         }
      }

      System.out.println(Thread.currentThread().getName() + " has finished executing.");
   }

   public static void main(String[] args) {
      new ThreadDemo("Thread 1");
      new ThreadDemo("Thread 2");
      new ThreadDemo("Thread 3");
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

Thread 1 yielding control...
Thread 2 yielding control...
Thread 3 yielding control...
Thread 3 has finished executing.
Thread 1 has finished executing.
Thread 2 has finished executing.
java_lang_thread.htm
廣告

© . All rights reserved.