简体   繁体   English

守护程序线程行为Java

[英]Daemon thread behavior java

What I know about Daemon thread is, JVM will exit if there is no user thread running and all remaining thread are of type Daemon. 我对Daemon线程的了解是,如果没有用户线程在运行并且所有其余线程均为Daemon类型,则JVM将退出。

When I run the program below, I always see output as "Main Thread ending" as 1st line and the prints "Hello from Worker 0" and so on until few more lines". 当我运行下面的程序时,我总是看到输出为“主线程结束”作为第一行,并显示“来自Worker 0的Hello”,依此类推,直到出现几行为止。

What my question is if Worker thread is set as Daemon then when the main thread ends, Worker thread should die and not go ahead but still "Hello from Worker 0" and son on lines are printed and after some time only JVM end, why it is behaving like this? 我的问题是,如果将工作线程设置为守护程序,那么当主线程结束时,工作线程应该死掉而不会继续前进,但是仍然打印“来自工作线程0的问候”和在线上的子行,并且在一段时间后仅JVM结束了,为什么呢?是这样吗?

I am sorry if my question is not valid but I want to know answer and have doubt in mind. 抱歉,如果我的问题无效,但我想知道答案并有疑问。

public class Test {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new WorkerThread().start() ;
        System.out.println("Main Thread ending") ;
    }

}
class WorkerThread extends Thread {

    public WorkerThread() {
        setDaemon(true) ;   
    }

    public void run() {
        int count=0 ;
        while (true) {
            System.out.println("Hello from Worker "+count++) ;
            count++;
        }
    }
}

Output 输出量

Main Thread ending
Hello from Worker 0
Hello from Worker 2
Hello from Worker 4
Hello from Worker 6
Hello from Worker 8

Thanks 谢谢

.... but still "Hello from Worker 0" and son on lines are printed and after some time only JVM end, why it is behaving like this? ....但仍然打印“ Worker 0的Hello消息”和子行,并且一段时间后只有JVM结束,为什么它会这样?

The most likely explanation is that worker thread wrote those lines to the System.out buffers either before the JVM noticed that the main thread had exited, or while it was going other cleanup work as part of the JVM shutdown. 最可能的解释是,工作线程在JVM注意到主线程退出之前,或者在进行其他清理工作(作为JVM关闭的一部分)之前,将这些行写入了System.out缓冲区。

But at the end of the day, it is unlikely that the extra output matters, so I'd advise that you ignore it. 但总而言之,额外的输出不太可能很重要,因此我建议您忽略它。 (Eliminating it could be rather difficult ...) (消除它可能相当困难...)

实际上并不能保证主线程在打印该行后立即退出,因此仍然有一个时间窗口,守护程序线程可以在其中打印某些内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM