Java Daemon Thread

 

Java Daemon Thread

Daemon threads is a low priority thread that provide supports to user threads. These threads can be user defined and system defined as well. Garbage collection thread is one of the system generated daemon thread that runs in background. These threads run in the background to perform tasks such as garbage collection. Daemon thread does allow JVM from existing until all the threads finish their execution. When a JVM founds daemon threads it terminates the thread and then shutdown itself, it does not care Daemon thread whether it is running or not.


Following are the methods in Daemon Thread

1. void setDaemon(boolean status)

In Java, this method is used to create the current thread as a daemon thread or user thread. If there is a user thread as obj1 then obj1.setDaemon(true) will make it a Daemon thread and if there is a Daemon thread obj2 then calling obj2.setDaemon(false) will make it a user thread.

Syntax:




public class DaemonDemo1 extends Thread 

    public DaemonDemo1(String name1)

    { 

        super(name1); 

    } 

    public void run() 

    {  

        if(Thread.currentThread().isDaemon()) 

        {  

            System.out.println(getName() + " is Daemon thread");  

        }  

        else

        {  

            System.out.println(getName() + " is User thread");  

        }  

    }  

    public static void main(String[] args) 

    {  

        DaemonDemo1 D1 = new DaemonDemo1("D1"); 

        DaemonDemo1 D2 = new DaemonDemo1("D2"); 

        DaemonDemo1 D3 = new DaemonDemo1("D3"); 


        D1.setDaemon(true);      

        D1.start();  

        D2.start(); 

        D3.setDaemon(true);  

        D3.start();         

    }  

}








No comments

JavaFX Scene Builder

  This is an article about the JavaFX Scene Builder. You will get a short introduction about the installation and usage of the software. The...