What is Daemon Thread in Java? How to create a Daemon Thread in Java?
Daemon Thread in Java is a service provider thread with low-priority.
Daemon threads performs background tasks such as garbage collection and also provides services to the user thread.
Most of the JVM threads are daemon threads.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class MyDaemon implements Runnable { Thread thread; MyDaemon() { thread = new Thread(this); thread.setDaemon(true); thread.start(); } public boolean isDaemon(){ return thread.isDaemon(); } public void run() { try { while(true) { System.out.print("."); Thread.sleep(100); } } catch(Exception exc) { System.out.println("MyDaemon interrupted."); } } } public class Main { public static void main(String args[]) throws Exception{ MyDaemon dt = new MyDaemon(); if(dt.isDaemon()) System.out.println("dt is a daemon thread."); Thread.sleep(10000); System.out.println("\nMain thread ending."); } } |