How To Create Daemon Thread In Java

Introduction

 
In this article, we discuss how to create a Daemon thread in Java.
 

Daemon Thread in Java

 
Basically there are two types of threads in Java, a daemon thread and a user thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads, in other words when all the user threads die, the JVM terminates this thread automatically.
 
Some points to remember about Daemon Thread
  • A Daemon Thread provides services to a user thread for background supporting tasks. It has no other role in life than to serve user threads.
  • Its life depends on user threads.
  • It is a low priority thread.
Why the JVM stops the daemon thread if there is no user thread remaining?
 
The basic purpose of a daemon thread is to provide services to a user thread for background support purposes. If there is no user thread then there is no reason for the JVM to keep running this thread. That is why the JVM stops the daemon thread if there is no user thread.
 
Methods for daemon thread
 
boolean isDaemon()
 
Determines whether the current thread is a Daemon thread.
void setDaemon(boolean status)
 
Marks the current thread as a daemon thread or user thread.
 
Example
  1. class DaemonThreadEx extends Thread  
  2.   {  
  3.     public void run()  
  4.       {  
  5.         System.out.println("Name Of Thread: "+ Thread.currentThread().getName());  
  6.         System.out.println("Daemon Thread: "+ Thread.currentThread().isDaemon());  
  7.       }  
  8.     public static void main(String[] args)  
  9.       {  
  10.         DaemonThreadEx th1=new DaemonThreadEx();  
  11.         DaemonThreadEx th2=new DaemonThreadEx();  
  12.         th1.setDaemon(true);  
  13.         th1.start();  
  14.         th2.start();  
  15.       }  
  16.   }   
Output
 
Fig-1.jpg
 
Note
 
If we need to make a user thread a Daemon then the thread must not be started otherwise it will throw IllegalThreadException.
  1. class DaemonThreadEx1 extends Thread   
  2. {  
  3.  public void run()   
  4.  {  
  5.   System.out.println("Name Of Thread: " + Thread.currentThread().getName());  
  6.   System.out.println("Daemon Thread: " + Thread.currentThread().isDaemon());  
  7.  }  
  8.  public static void main(String[] args)   
  9.  {  
  10.   DaemonThreadEx1 th1 = new DaemonThreadEx1();  
  11.   DaemonThreadEx1 th2 = new DaemonThreadEx1();  
  12.   th1.start();  
  13.   th1.setDaemon(true);  
  14.   th2.start();  
  15.  }  
  16. }   
Output
 
Fig-2.jpg
 


Similar Articles