Junior — Middle
Can you explain what a demon thread is and how it differs from a regular thread?
sobes.tech AI
Answer from AI
A daemon thread in Java is a background thread that does not prevent the JVM from exiting. The main difference from a regular (user) thread is that the JVM automatically terminates when all user threads have finished, even if daemon threads are still running.
Features of daemon threads:
- They are intended for background tasks, such as garbage collection.
- They do not block the program from terminating.
- You can set a thread as a daemon using the
setDaemon(true)method before starting the thread.
Example:
Thread daemonThread = new Thread(() -> {
while (true) {
System.out.println("Daemon thread is running");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
});
daemonThread.setDaemon(true);
daemonThread.start();
System.out.println("Main thread has finished");
In this example, when the main thread finishes, the JVM will automatically stop the daemon thread.