Daemon Thread in Java



The threads which hare running in the background to provide support for user defined threads are called “Daemon Thread”. Usually daemon thread are running with low priority but based on our requirement we can increase their priority also. We can check whether the given thread is daemon or not by using the following thread class thread. public boolean isDaemon() we can change the daemon nature of a thread by using setDaemon() method of thread class.

public void setDaemon(Boolean b)

the daemon nature of a thread is inheriting from the parent. i.e if the parent is daemon then the child is also daemon and if the parent is non – daemon then the child is also non – daemon. After starting a thread we are not allowed to change the daemon nature violation leads to runtime exception saying IllegalThreadStateException.

Example:

class MyThread extends Thread 
{

}

class Test 
{
    public static void main(String arg[])
    {
        System.out.println(Thread.currentThread().isDaemon());
        MyThread t = new MyThread();
        System.out.println(t.isDaemon());
        t.setDaemon(true);
        System.out.println(t.isDaemon());
        t.start();
     //t.setDaemon(false); // 1
    }

}

Output:

false
false
true


If we don’t comment line 1 we will get the IlleagalThreadStateException, see the following 

Output:

false
false
true
Exception


We can’t change the daemon nature of main thread because it has started already before main() method only. All the daemon threads will be terminated automatically when ever last non – daemon thread terminates.

Example:

class MyThread extends Thread
{
    public void run()
    {
        for (int i = 0; i < 10; i++) 
        {
            System.out.println("Child Thread");
            try 
            {
                Thread.sleep(1000);
            } 
            catch (InterruptedException e)
            {
                System.out.println(e);
            }
        }
    }
}

class DaemonThreadDemo 
{
    public static void main(String arg[]) {
        MyThread t = new MyThread();
        t.setDaemon(true);// 1
        t.start();
        System.out.println("The end of main");
    }

}

Output:

child Thread
the end of main thread

If we are commenting line 1, then both child and main threads are non – Daemon, hence they will execute until their completion. If we are not commenting line 1, then the child thread is daemon and hence it will terminate automatically when ever main() thread terminates.



No comments:

Post a Comment