Threads · Topic 5 of 7
Daemon threads
Definition​
A daemon thread is a background helper. The JVM does not wait for daemon threads: when only daemon threads are left, the program ends. Normal (non-daemon) threads keep the program alive until they finish.
Example code​
A daemon thread does not keep the program alive
class Demo {
public static void main(String[] args) {
Thread background = new Thread(() -> {
while (true) { // would run forever...
try { Thread.sleep(100); } catch (InterruptedException e) { return; }
}
});
background.setDaemon(true); // ...but a daemon cannot block shutdown
background.start();
System.out.println("is daemon: " + background.isDaemon());
System.out.println("main is done, the JVM exits even though the daemon is still running");
}
}
// Output:
// is daemon: true
// main is done, the JVM exits even though the daemon is still running
Finished this page? Track your progress (saved only in your browser).