Multithreading - Daemon Threads

Daemon threads are threads that run in the background. The best example for that is Garbage Collector.

Java provides following methods related to daemon threads :

1. isDaemon() - check if the thread is a daemon thread
2. setDaemon() - set the thread to be a daemon thread

By default, the main thread is not a daemon thread. All the child threads inherit the daemon nature from the thread that creates them.

public class DaemonThreadExample {
    public static void main(String[] args) {
        MyThreadExtendingThreadClass t = new MyThreadExtendingThreadClass();        t.setDaemon(true);        t.start(); // check till how many outputs it generates on the console
        System.out.println(Thread.currentThread().isDaemon());        System.out.println("Main thread completed");       }
}


Daemon threads are automatically terminated when all the non-daemon threads have finished execution.

The example for daemon thread can be found here

Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures