チュートリアル ポイントからの Java のサンプル プログラムを次に示します。
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
プログラムの出力は次のとおりです。
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
メイン スレッドが子スレッドの前に実行される理由がわかりません。プログラムでは、最初に new NewThread() が実行されることがわかります。NewThread クラスは新しいスレッドをインスタンス化し、その新しいスレッドで start() 関数を呼び出し、それから run() 関数を呼び出します。メイン関数のループは、新しいスレッドが作成された後にのみ発生します。ただし、プログラムを実行すると、メインスレッドのループが子スレッドの前に実行されます。理解を助けてください。