What is the Daemon Thread in Java? Give an example?
In Java, a daemon thread is a thread that runs in the background to perform tasks that do not prevent the JVM from exiting when the program finishes. Daemon threads are typically used for background tasks such as garbage collection, monitoring, or other housekeeping tasks. When all user (non-daemon) threads finish executing, the JVM will terminate, even if daemon threads are still running.
setDaemon(true)
method before starting the thread.Here’s a simple example demonstrating how to create and use a daemon thread in Java:
class DaemonThreadExample extends Thread {
public void run() {
while (true) {
System.out.println("Daemon thread is running...");
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println("Daemon thread interrupted.");
}
}
}
}
public class Main {
public static void main(String[] args) {
DaemonThreadExample daemonThread = new DaemonThreadExample();
daemonThread.setDaemon(true); // Set the thread as a daemon
daemonThread.start(); // Start the daemon thread
// Main thread sleeps for 5 seconds
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread is finishing...");
// When the main thread finishes, the JVM will exit, and the daemon thread will be terminated.
}
}
Thread
and overrides the run()
method to print a message in an infinite loop.When you run the above code, you will see the message from the daemon thread printed every second for 5 seconds, after which the main thread finishes, and the program exits. The daemon thread will not continue running after the main thread has completed.