How do I check if a thread is a daemon thread?

You can test if a thread is a daemon thread or a user thread by calling the isDaemon() method of the Thread class. If it returns true then the thread is a daemon thread, otherwise it is a user thread.

package org.kodejava.lang;

public class ThreadCheckDaemon implements Runnable {
    public static void main(String[] args) {
        Thread t1 = new Thread(new ThreadCheckDaemon(), "FirstThread");
        Thread t2 = new Thread(new ThreadCheckDaemon(), "SecondThread");

        t1.setDaemon(true);
        t1.start();
        t2.start();

        if (t1.isDaemon()) {
            System.out.format("%s is a daemon thread.%n", t1.getName());
        } else {
            System.out.format("%s is a user thread.%n", t1.getName());
        }

        if (t2.isDaemon()) {
            System.out.format("%s is a daemon thread %n", t2.getName());
        } else {
            System.out.format("%s is a user thread %n", t2.getName());
        }
    }

    public void run() {
        System.out.println("Running [" +
                Thread.currentThread().getName() + "]");
    }
}

The code snippet print the following output:

FirstThread is a daemon thread.
SecondThread is a user thread 
Running [FirstThread]
Running [SecondThread]

How do I create a daemon thread?

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. To create a daemon thread, call setDaemon() method with a true boolean value as argument before the thread is started.

package org.kodejava.lang;

public class DaemonThread implements Runnable {
    private final String threadName;

    private DaemonThread(String threadName) {
        this.threadName = threadName;
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new DaemonThread("FirstThread"));
        Thread t2 = new Thread(new DaemonThread("SecondThread"));

        // t1 is as daemon thread
        t1.setDaemon(true);
        t1.start();

        // t2 is a user thread
        t2.start();
    }

    public void run() {
        System.out.println("Running [" + threadName + "]");
    }
}