【问题标题】:Java: Can a child thread outlive the main thread [duplicate]Java:子线程能否比主线程寿命长[重复]
【发布时间】: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() 所有子线程。

标签: java java-9


【解决方案1】:

根据Thread#setDaemondocumentation

当唯一运行的线程都是守护线程时,Java 虚拟机退出。

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

【讨论】:

  • 我还会在(正确的)答案中添加一个事实,即 JVM 线程实际上并没有“父”的概念。 “父”线程可以完成并可以回收其内存,而“子”可以继续运行。
  • 守护线程在 Windows 上有很多问题;基本上,它们不起作用。
猜你喜欢
  • 2013-10-22
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
  • 2013-02-21
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多