简体   繁体   中英

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.

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".

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?

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?

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.

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 ...)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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