JAVA

他のスレッドの終了を待つスレッドを作る

下記のようなソースを書きます。
[c]
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");
}

}

[/c]

実行すると次のようなメッセージがコンソールに表示されます
[c]
main start
main wait
run start
run end
main end
[/c]

いったい何が起きているのかというと、
[c]
JoinTest th = new JoinTest();
[/c]
でいったんスタートしたthというスレッドのインスタンスが実行している間に、
[c]
th.join();
[/c]
というメソッドが起動したタイミングで
[c]
public void run(){
[/c]
のメソッドで定義した別スレッドが起動され、その終了をthというスレッドが待っている状態になっています。

他のスレッドの終了を待ってからメインだったスレッドが再開する。という動作ができます。

注意として、joinというメソッドの使い方には3つの方法があります。
[c]
//タイムアウトなし、スレッドの終了を待つ
void join() throws InterruptedException

//タイムアウトあり、スレッドの終了を待つ(ミリ秒)
void join(long msec) throws InterruptedException

//タイムアウトあり、スレッドの終了を待つ(ミリ秒+ナノ秒)
void join(long msec, int nsec) throws InterruptedException
[/c]

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です