Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn't terminates unless all the user thread terminate.
On the other hand we have Daemon threads. These threads are generally 'Service provider' threads. They should not be used to execute your program code but system code. These thread run in parallel to your code but JVM can kill them anytime. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus you should never depend on daemon thread to perform any program code.
Basically daemon threads exist only to do some work for non-daemon threads. If the only threads left in the JVM are daemon, then your program exits (terminates).
You might want to check and run the code below. You'll notice that when making thread t daemon, it exits immediately after the only non-daemon thread (the main thread) finishes - i.e. the daemon thread has not time to count from 10 to 1. But if you make thread t non-daemon, it finishes its job to the end (counting from 10 to 1).
import static java.util.concurrent.TimeUnit.*;
public class DaemonTest{
public static void main(String args[]) throws InterruptedException{
Runnable r = new Runnable(){
public void run(){
for(int time = 10; time > 0; --time){
System.out.println("Time #" + time);
try{
SECONDS.sleep(2);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.setDaemon(true);
t.start();
System.out.println("Main thread waiting...");
SECONDS.sleep(6);
System.out.println("Main thread exited.");
}
}