Daemon and Non-Daemon threads are created via JVM. Main method is non-daemon thread or user thread that are terminated automatically when all non-daemon threads in the program have finished or when the main application exits.
If you want to create any non-daemon thread as daemon then we can set as setDaemon(true).
Examples of daemon threads include the garbage collector in Java or background service threads in server applications.
Non-daemon threads keep the application alive until they complete their task or are explicitly terminated.
In summary, daemon and non-daemon threads serve different purposes in a multithreaded application, with daemon threads typically performing background tasks and non-daemon threads handling critical application functionality.
public class DaemonExample {
public static void main(String[] args) {
// Creating a daemon thread
Thread daemonThread = new Thread(() -> {
while (true) {
System.out.println("Daemon thread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
daemonThread.setDaemon(true); // Set the thread as daemon
daemonThread.start();
// Creating a non-daemon thread
Thread nonDaemonThread = new Thread(() -> {
int count = 0;
while (count < 5) {
System.out.println("Non-daemon thread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
});
nonDaemonThread.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread exiting");
}
}
Informative ..
Informative