Tuesday, 4 February 2014

What are daemon Threads in java??

Daemon Thread:-
                            There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM termintates this thread automatically.


lets discuss this with an example....

public class UserThreadClass{

    public static void main(String[] args) {
        new DaemonThread().start();
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {}
        System.out.println("Main Thread ending") ;
    }

}
class DaemonThread extends Thread {

    public DaemonThread() {
        setDaemon(true) ;   // When false, (i.e. when it's a user thread),
                // the Daemon  thread continues to run.
                // When true, (i.e. when it's a daemon thread),
                // the Daemon thread terminates when the main 
                // thread terminates.
    }

    public void run() {
        int count=0 ;
        while (count<5) {
            System.out.println("Hello from Daemon "+count++) ;
            try {
                sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}

Try to run this program with setDaemon(true) and again with setDaemon(false) in both cases you will see the difference in execution.
when setDaemon is true then main thread will terminate when its all lines of code execution completed ,JVM also kill DaemonThread .

But when it is set to false, JVM will not terminate the Daemon thread till its run method executed completely.

No comments:

Post a Comment