Java 併發性 – join() 方法


join 函式

此函式用於將一個執行緒的執行開始部分連線到另一個執行緒的執行末尾。這樣,可以確保在第二個執行緒停止執行之前,第一個執行緒不會執行。此函式等待特定毫秒數,直到執行緒終止。

請看以下示例 −

示例

 動態演示

import java.lang.*;
public class Demo implements Runnable{
   public void run(){
      Thread my_t = Thread.currentThread();
      System.out.println("The name of the current thread is " + my_t.getName());
      System.out.println("Is the current thread alive? " + my_t.isAlive());
   }
   public static void main(String args[]) throws Exception{
      Thread my_t = new Thread(new Demo());
      System.out.println("The instance has been created and started");
      my_t.start();
      my_t.join(30);
      System.out.println("The threads will be joined after 30 milli seconds");
      System.out.println("The name of the current thread is " + my_t.getName());
      System.out.println("Is the current thread alive? " + my_t.isAlive());
   }
}

輸出

The instance has been created and started
The threads will be joined after 30 milli seconds
The name of the current thread is Thread-0
The name of the current thread is Thread-0
Is the current thread alive? true
Is the current thread alive? true

名為 Demo 的一個類實現了 Runnable 類。定義了一個“run”函式,將當前執行緒指定為新建立的 Thread。在主函式中,建立了該執行緒的一個新例項,並使用“start”函式開始該執行緒。該執行緒在特定時間後與另一個執行緒 join。螢幕上顯示相關訊息。

更新於: 04-Jul-2020

443 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.