Java: 子线程能否比主线程长寿
Java: Can a child thread outlive the main thread
我在 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();
}
}
}
}
有什么地方我没看懂……或者这是 Java 从 JDK 9 开始的新功能?
根据Thread#setDaemon
的documentation:
The Java Virtual Machine exits when the only threads running are all daemon threads.
您的子线程不是守护线程,因此即使主线程不再运行,JVM 也不会退出。如果在NewThread
的构造函数中调用t.setDaemon(true);
,那么JVM会在主线程执行完后退出。
我在 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();
}
}
}
}
有什么地方我没看懂……或者这是 Java 从 JDK 9 开始的新功能?
根据Thread#setDaemon
的documentation:
The Java Virtual Machine exits when the only threads running are all daemon threads.
您的子线程不是守护线程,因此即使主线程不再运行,JVM 也不会退出。如果在NewThread
的构造函数中调用t.setDaemon(true);
,那么JVM会在主线程执行完后退出。