articles

Home / DeveloperSection / Articles / Daemon Thread in Java

Daemon Thread in Java

Anupam Mishra4028 10-Dec-2015

 In java, Damon thread is a low priority thread .It is used for providing background support to any user thread to same process as the daemon thread. If you want to make any user threads to as a daemon thread then it must not be started otherwise, throw exception. Its life or role depends upon user level threads.

Daemon thread is very useful for the background tasks and only needed while normal thread are executing and normal thread are set as a daemon thread. For setting a user thread to a daemon thread, we using a setDaemon (boolean status)method to user level thread.

For checking current thread is a daemon or not, we using Thread.currentThread().isDaemon() method that returns true or false.

If any user thread are not running then JVM terminates the daemon thread automatically.

For Example, we have taken 3 threads t1, t2 and t3 respectively and before starting thread t1 we set as Daemon to thread t1.   

public class DaemonThread extends Thread{ 
public void run(){
if(Thread.currentThread().isDaemon()){
       System.out.println("Daemon Thread Is Working");
  }
  else{
       System.out.println("User Thread is Running ");
 }
 }
 public static void main(String[] args){
   DaemonThread t1=new DaemonThread();
 DaemonThread t2=new DaemonThread();
   DaemonThread t3=new DaemonThread();
    t1.setDaemon(true); //now t1 is daemon thread
    t1.start();//starting threads
    t2.start();
    t3.start();
 }
}  


Daemon Thread in Java 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By