Java 執行緒 join() 方法



描述

Java Thread join() 方法等待此執行緒終止。

宣告

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

public final void join() throws InterruptedException

引數

返回值

此方法不返回值。

異常

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();
	  
      t.join();
      System.out.print(t.getName());
      
      //checks if this thread is alive
      System.out.println(", status = " + t.isAlive());
   }
} 

輸出

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

Thread-0, status = true
Thread-0, status = false
java_lang_thread.htm
廣告