メインスレッドは子スレッドの処理が完了するまで待ち、子スレッドの完了を受けてから End of main を出力する。
Example: java_thread_01.java
public class java_thread_01 extends Thread {
public static void main(String args[]) {
System.out.println("Start of main");
/* 子スレッド生成、スタート */
java_thread_01 thread = new java_thread_01("Child Thread");
thread.start();
/* 子スレッドの終了を待つ */
try {
thread.join();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("End of main");
}
/* 子スレッドの初期化 */
public java_thread_01(String name) {
super(name);
}
public void run() {
/* 子スレッドの処理 */
int i;
for (i = 0; i < 5; i++) {
System.out.println(this.getName() + ": " + i);
try {
sleep(500); // 500msec 停止
}
catch (InterruptedException e) {
}
}
System.out.println(this.getName() + ": End");
}
}
実行結果
> javac java_thread_01.java > java java_thread_01 Start of main Child Thread: 0 Child Thread: 1 Child Thread: 2 Child Thread: 3 Child Thread: 4 Child Thread: End End of main

0 件のコメント:
コメントを投稿