【问题标题】:Why setdaemon property is not ending the child thread when main thread has ended?为什么当主线程结束时 setdaemon 属性没有结束子线程?
【发布时间】:2019-06-05 07:21:07
【问题描述】:

我正在运行以下代码以了解守护线程概念和线程终止。即使在 main 方法完成后,程序也会继续打印。我在这里错过了什么吗?

package threading;

public class ThreadInterruption {

    public static void main(String[] args) {
        Thread t = new Thread(new RanThread());
        t.start();
        t.setDaemon(true);
        t.interrupt();
    }

}

class RanThread implements Runnable{

    @Override
    public void run() {
        int count=0;
        while(true) {
            System.out.println("Ha Ha Ha "+ count);
            count=count+1;

        }

    }


}

提前致谢。

【问题讨论】:

    标签: java multithreading daemon


    【解决方案1】:

    您必须在启动线程之前将其设置为守护进程。

    如果您阅读 API 文档,它会声明“必须在线程启动之前调用此方法。”

    所以交换 start 和 setDaemon 行,你应该很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 2021-06-21
      • 2022-08-06
      相关资源
      最近更新 更多