Java Thread join() 方法



描述

Java Thread join(long millis) 方法最多等待 millis 毫秒,直到此執行緒終止。超時值為 0 表示無限期等待。

宣告

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

public final void join(long millis) throws InterruptedException

引數

millis − 等待時間(毫秒)。

返回值

此方法不返回值。

異常

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 for
         this thread to die */
      t.join(2000);
      System.out.println("after waiting for 2000 milliseconds...");
      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...
Thread-0, status = false
java_lang_thread.htm
廣告
© . All rights reserved.