下記のようなソースを書きます。
package ThreadPackage;
public class JoinTest extends Thread {
/**
* @param args
*/
public static void main(String[] args) {
JoinTest th = new JoinTest();
System.out.println("main start");
th.start();
System.out.println("main wait");
try{
th.join();
} catch(InterruptedException e){
System.out.println(e);
}
System.out.println("main end");
}
public void run(){
System.out.println("run start");
try {
Thread.sleep(3000);
}catch(InterruptedException e){
System.out.println(e);
}
System.out.println("run end");
}
}
実行すると次のようなメッセージがコンソールに表示されます
main start main wait run start run end main end
いったい何が起きているのかというと、
JoinTest th = new JoinTest();
でいったんスタートしたthというスレッドのインスタンスが実行している間に、
th.join();
というメソッドが起動したタイミングで
public void run(){
のメソッドで定義した別スレッドが起動され、その終了をthというスレッドが待っている状態になっています。
他のスレッドの終了を待ってからメインだったスレッドが再開する。という動作ができます。
注意として、joinというメソッドの使い方には3つの方法があります。
//タイムアウトなし、スレッドの終了を待つ void join() throws InterruptedException //タイムアウトあり、スレッドの終了を待つ(ミリ秒) void join(long msec) throws InterruptedException //タイムアウトあり、スレッドの終了を待つ(ミリ秒+ナノ秒) void join(long msec, int nsec) throws InterruptedException