What is daemon thread and which method is used to create the daemon thread

Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

In Java, a daemon thread is a thread that runs in the background and provides services to user threads or performs tasks such as garbage collection. The Java Virtual Machine (JVM) exits when all user threads finish their execution. However, it doesn’t wait for daemon threads to complete. If all the remaining threads in the JVM are daemon threads, the JVM will exit.

To create a daemon thread in Java, you can use the setDaemon(true) method of the Thread class before starting the thread. Here’s an example:

java
public class DaemonThreadExample {
public static void main(String[] args) {
Thread daemonThread = new Thread(() -> {
// Daemon thread code
for (int i = 0; i < 5; i++) {
System.out.println("Daemon Thread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

// Set the thread as daemon
daemonThread.setDaemon(true);

// Start the daemon thread
daemonThread.start();

// Main thread code
for (int i = 0; i < 3; i++) {
System.out.println("Main Thread: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

In this example, daemonThread.setDaemon(true) is used to set the daemon property of the thread, and then daemonThread.start() is called to start the daemon thread. The main thread and daemon thread run concurrently. The daemon thread will exit when the main thread finishes, or when all non-daemon threads finish their execution.