Reputation: 6111
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++;
}
}
}
Main Thread ending
Hello from Worker 0
Hello from Worker 2
Hello from Worker 4
Hello from Worker 6
Hello from Worker 8
Thanks
Upvotes: 1
Views: 311
Reputation: 62469
It's not really guaranteed anywhere that the main thread exits immediately after printing that line, so there could still be a time window in which the daemon threads could print something.
Upvotes: 2
Reputation: 719659
.... 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 ...)
Upvotes: 3