このコードを理解するのに問題があります。私は 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.
これが私の質問です。
コードがたどるパターンを理解したい。私によると、
- まず、プログラムは
main()
関数の実行を開始する必要があります。そのため、NewThread のインスタンスを初期化する必要があります。 - 次に、NewThread コンストラクターに入り、次のように記述します。
Child thread: Thread[Demo Thread,5,main]
- その後 t.start() が来るので、プログラムを実行する必要があります
public void run()
(AM I WRONG HERE ?? )
ではpublic void run()
、出力を取得する必要があったと思いますChild Thread 5
が、代わりに を取得しMain Thread 5
ました。なぜだろう??
私を助けてくれる人はいますか?? 前もって感謝します。