Java Thread joinメソッドは、指定されたスレッドが終了するまで現在のスレッドの実行を一時停止するために使用できます。オーバーロードされたjoin関数が3つあります。
Java Thread join
public final void join():このJavaスレッドのjoinメソッドは、呼び出されたスレッドが終了するまで現在のスレッドを待機状態にします。スレッドが割り込まれると、InterruptedExceptionがスローされます。public final synchronized void join(long millis):このJavaスレッドのjoinメソッドは、呼び出されたスレッドが終了するか、指定されたミリ秒待機します。スレッドの実行はOSの実装に依存するため、現在のスレッドが指定された時間だけ待機することは保証されません。public final synchronized void join(long millis, int nanos):このJavaスレッドのjoinメソッドは、指定されたミリ秒とナノ秒に加えて、スレッドが終了するのを待機するために使用されます。以下は、Thread joinメソッドの使用例を示すシンプルな例です。プログラムの目標は、mainが最後に完了し、3番目のスレッドが最初のスレッドが終了した後にのみ開始されることを確認することです。
package com.journaldev.threads;
public class ThreadJoinExample {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable(), "t1");
Thread t2 = new Thread(new MyRunnable(), "t2");
Thread t3 = new Thread(new MyRunnable(), "t3");
t1.start();
// 2秒待ってから第二のスレッドを開始するか、それが終了した場合
try {
t1.join(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
// 最初のスレッドが終了した場合にのみ第三のスレッドを開始
try {
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
t3.start();
// メインスレッドを終了する前にすべてのスレッドの実行が終了する
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
// TODO 自動生成された例外キャッチブロック
e.printStackTrace();
}
System.out.println("All threads are dead, exiting main thread");
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("Thread started:::"+Thread.currentThread().getName());
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread ended:::"+Thread.currentThread().getName());
}
}
上記のプログラムの出力は:
Thread started:::t1
Thread started:::t2
Thread ended:::t1
Thread started:::t3
Thread ended:::t2
Thread ended:::t3
All threads are dead, exiting main thread
これで、Javaスレッドのjoinの例に関する簡単なまとめが終了です。
Source:
https://www.digitalocean.com/community/tutorials/java-thread-join-example