1. The threads which hare running in the background to provide support for user defined threads are called “Daemon Thread”.
  2. Usually daemon thread are running with low priority but based on our requirement we can increase their priority also.
  3. We can check whether the given thread is daemon or not by using the following thread class method.
    public final boolean isDaemon()
  4. we can change the daemon nature of a thread by using setDaemon() method of thread class.
    public final void setDaemon(Boolean b)
  5. The daemon nature of a thread is inheriting from the parent. i.e if the parent is daemon then the child is also daemon and if the parent is non-daemon then the child is also non–daemon.
  6. After starting a thread we are not allowed to change the daemon nature violation leads to run time exception saying IllegalThreadStateException.

Example:

public class TestThreadDemo {
	 
    
    public static void main(String[] args) {
     
        System.out.println(Thread.currentThread().isDaemon());
        TestThread testThread=new TestThread();
        System.out.println(testThread.isDaemon());
        testThread.setDaemon(true);
        System.out.println(testThread.isDaemon());
        testThread.start();
    }
}
 
class TestThread extends Thread{
    public void run(){
        System.out.println("run method");
    }
}
/*
Output:
false
false
true
run method
*/

We can’t change the daemon nature of main thread because it has started already before main() method only.All the daemon threads will be terminated automatically when ever last non – daemon thread terminates.

public class DaemonThreadDemo {
	 
    public static void main(String[] args) {
        ChildThredDemo childThredDemo=new ChildThredDemo();
        childThredDemo.setDaemon(true);//--------------->1
        childThredDemo.start();
        System.out.println("The end of main");
 
    }
 
}
 
class ChildThredDemo extends Thread{
    public void run(){
        for(int i=1;i<=10;i++){
            System.out.println("Child Thread.");
            try{
                Thread.sleep(500);
            }catch(InterruptedException exception){
                 
            }
        }
    }
}
/*
Output:
The end of main
Child Thread.
*/

Note:

  1. If we are commenting line 1, then both child and main threads are non – Daemon, hence they will execute until their completion.
  2. If we are not commenting line 1, then the child thread is daemon and hence it will terminate automatically when ever main() thread terminates.