Java Thread join() 方法



描述

Java Thread join(long millis, int nanos) 方法最多等待 millis 毫秒加上 nanos 納秒,直到該執行緒結束。

宣告

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

public final void join(long millis, int nanos) throws InterruptedException

引數

  • millis - 這是要等待的毫秒數。

  • nanos - 這是要額外等待的 999999 納秒。

返回值

此方法不返回值。

異常

  • IllegalArgumentException - 如果 millis 的值為負數,或者 nanos 的值不在 0-999999 範圍內。

  • InterruptedException - 如果任何執行緒中斷了當前執行緒。當丟擲此異常時,當前執行緒的中斷狀態將被清除。

示例:使執行緒等待

以下示例演示了 Java Thread join() 方法的使用。在此程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在建構函式中,使用 currentThread() 方法獲取當前執行緒。列印其名稱,並使用 isAlive() 檢查執行緒是否處於活動狀態。

在 main 方法中,我們使用 ThreadDemo 建立了一個執行緒,並使用 start() 方法啟動執行緒。現在,使用 join() 使執行緒等待給定的時間段,然後列印執行緒名稱,並再次使用 isAlive() 列印其處於活動狀態。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   public void run() {

      Thread t = Thread.currentThread();
      System.out.print(t.getName());
      
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }

   public static void main(String args[]) throws Exception {

      Thread t = new Thread(new ThreadDemo());
      
      // this will call run() function
      t.start();
      /* waits at most 2000 milliseconds plus 500 nanoseconds for
         this thread to die */
      t.join(2000, 500);
      System.out.println("after waiting for 2000 milliseconds plus 500 nanoseconds ...");
      System.out.print(t.getName());
      
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }
} 

輸出

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

Thread-0, status = true
after waiting for 2000 milliseconds plus 500 nanoseconds ...
Thread-0, status = false
java_lang_thread.htm
廣告