A daemon thread is a low-priority thread whose purpose is to provide services to user threads.
Since daemon threads are only required when the user threads are operating, they do not prevent the JVM from quitting after all the user threads have completed execution.
Infinite loops, which are common in daemon threads, do not cause issues because no code (including finally
blocks) is executed until all the user threads have completed execution. Therefore, daemon threads should not be used for I/O activities.
We can use the setDaemon
method of the Thread
class to create a daemon thread.
public final void setDaemon(boolean on)
on
: If the value is True
, then the current thread is marked as a daemon thread.This method doesn’t return anything.
public class Main{public static void main(String[] args) throws InterruptedException {Runnable runnable = () -> {if(Thread.currentThread().isDaemon()){System.out.println(Thread.currentThread().getName() + " is a daemon thread");}else{System.out.println(Thread.currentThread().getName() + " is not a daemon thread");}};Thread daemonThread = new Thread(runnable);daemonThread.setName("daemon-thread");daemonThread.setDaemon(true);Thread notDaemonThread = new Thread(runnable);notDaemonThread.setName("not-daemon-thread");daemonThread.start();notDaemonThread.start();Thread.sleep(1000);}}
Runnable
interface, runnable
. runnable
prints whether the current thread is a daemon thread or not with the help of the isDaemon()
method.daemonThread
, with the help of runnable
.daemonThread
thread "daemon-thread"
.setDaemon()
method to make the daemonThread
thread a daemon thread.notDaemonThread
, with the help of runnable
.notDaemonThread
thread "not-daemon-thread"
.start()
method to start the daemonThread
and notDaemonThread
threads.