【发布时间】:2018-04-01 03:29:49
【问题描述】:
我在 Java 中了解到:子线程不会比主线程寿命长,但是,看起来,这个应用程序的行为显示了不同的结果。
子线程继续工作,而主线程完成工作!
这是我的工作:
public class Main {
public static void main(String[] args) {
Thread t = Thread.currentThread();
// Starting a new child thread here
new NewThread();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("\n This is the last thing in the main Thread!");
}
}
class NewThread implements Runnable {
private Thread t;
NewThread(){
t= new Thread(this,"My New Thread");
t.start();
}
public void run(){
for (int i = 0; i <40; i++) {
try {
Thread.sleep(4000);
System.out.printf("Second thread printout!\n");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
我在这里不明白什么……或者这是从 JDK 9 开始的 Java 中的一个新特性?
【问题讨论】:
-
添加
System.exit(0);- 或join()所有子线程。