我在理解此代碼時遇到問題。我只有幾個小時的Java知識。基本的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()
(我錯了這裏?)
在public void run()
,我認爲我應該得到一個輸出Child Thread 5
,但我得到了Main Thread 5
。我想知道爲什麼 ??
有沒有人幫我?提前致謝。
精彩:Java威脅... :-) – Seelenvirtuose