Thread Daemon In Java Example
Chapter:
Thread
Last Updated:
15-07-2016 13:42:50 UTC
Program:
/* ............... START ............... */
public class JavaThreadDaemon {
public static void main(String[] args) {
Thread t = new Thread(JavaThreadDaemon::print);
t.setDaemon(true);
t.start();
System.out.println("Main Thread Exiting");
}
public static void print() {
int counter = 1;
while (true) {
try {
System.out.println("Counter:" + counter++);
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/* ............... END ............... */
Output
Main Thread Exiting
Counter:1
Notes:
-
A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running.
- Purpose of the daemon thread is that it provides services to user thread for background supporting task.
- If no user thread JVM keep running daemon thread.
- Daemon threads will be terminated by the JVM when there are none of the other threads running, it includs main thread of execution as well.
Tags
Thread Daemon, Java