我在理解这段代码时遇到了问题。我只有几个小时的 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
。我想知道为什么 ??
有人帮我吗??提前致谢。