User Thread vs Daemon Thread in Java?



The daemon threads are typically used to perform services for user threads. The main() method of the application thread is a user thread (non-daemon thread). The JVM doesn’t terminate unless all the user thread (non-daemon) terminates. We can explicitly specify a thread created by a user thread to be a daemon thread by calling setDaemon(true). To determine if a thread is a daemon thread by using the method isDaemon().

Example

public class UserDaemonThreadTest extends Thread {
   public static void main(String args[]) {
      System.out.println("Thread name is : "+ Thread.currentThread().getName());
      // Check whether the main thread is daemon or user thread
      System.out.println("Is main thread daemon ? : "+ Thread.currentThread().isDaemon());
      UserDaemonThreadTest t1 = new UserDaemonThreadTest();
      UserDaemonThreadTest t2 = new UserDaemonThreadTest();
      // Converting t1(user thread) to a daemon thread
      t1.setDaemon(true);
      t1.start();
      t2.start();
   }
   public void run() {
      // Checking threads are daemon or not
      if (Thread.currentThread().isDaemon()) {
         System.out.println(Thread.currentThread().getName()+" is a Daemon Thread");
      } else {
         System.out.println(Thread.currentThread().getName()+" is an User Thread");
      }
   }
}

Output

Thread name is : main
Is main thread daemon ? : false
Thread-0 is a Daemon Thread
Thread-1 is an User Thread

Advertisements