Java:子线程能比主线程活得长吗

Java:子线程能比主线程活得长吗,java,java-9,Java,Java 9,我在Java中了解到:子线程的寿命不会超过主线程,但是,这个应用程序的行为似乎显示了不同的结果 子线程继续工作,而主线程完成工作 以下是我的工作: public class Main { public static void main(String[] args) { Thread t = Thread.currentThread(); // Starting a new child thread here new NewThread(); try {

我在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();
        }
    }
}
公共类主{
公共静态void main(字符串[]args){
Thread t=Thread.currentThread();
//在这里开始一个新的子线程
新的NewThread();
试一试{
睡眠(1000);
}捕捉(中断异常e){
e、 printStackTrace();
}
System.out.println(“\n这是主线程中的最后一件事!”);
}
}
类NewThread实现Runnable{
私有线程t;
NewThread(){
t=新线程(这是“我的新线程”);
t、 start();
}
公开募捐{
对于(inti=0;i,根据
线程的设置守护进程

当运行的线程都是守护进程线程时,Java虚拟机将退出


您的子线程不是守护进程线程,因此即使主线程不再运行,JVM也不会退出。如果在
NewThread
的构造函数中调用
t.setDaemon(true);
,则JVM将在主线程完成执行后退出。

添加
System.exit(0);
-或
join()
所有子线程。我还要补充一个(正确的)答案,即JVM线程实际上没有“父线程”的概念。“父线程”可以完成,其内存可以回收,而“子线程”可以继续运行。守护进程线程在Windows上有大量问题;基本上,它们不工作。