How to create a daemon thread in java

A daemon thread is simply a background thread that is subordinate to the thread that creates it, so when the thread that created the daemon thread ends, the daemon thread dies with it.

A thread that is not a daemon thread is called a user thread. We cannot create a thread directly as daemon, first we need to create a user thread then we can convert user defined thread as daemon thread.

To create a daemon thread, You can call setDaemon() method on user defined thread with a true boolean value as argument before the thread is started.

 
 
package com.java.thread;
 
public class DaemonThreadExample implements Runnable {
 
    private String name;
 
    public DaemonThreadExample(String name) {
        this.name = name;
    }
 
    public void run() {
        System.out.println("Thread " + name + " running");
    }
 
    public static void main(String[] args) {
        Thread thread1 = new Thread(new DaemonThreadExample("First"));
        Thread thread2 = new Thread(new DaemonThreadExample("Second"));
 
        // Set thread1 is as daemon thread
        thread1.setDaemon(true);
        thread1.start();
 
        // thread2 is a user thread
        thread2.start();
        // Print the result to find the daemon thread or not.
        System.out.println("Thread1 is daemon thread : " + thread1.isDaemon());
        System.out.println("Thread2 is daemon thread : " + thread2.isDaemon());
    }
}
 
 
 

The output of the above example will be as below:

 
 
Thread1 is daemon thread : true
Thread2 is daemon thread : false
Thread Second running
Thread First running