Difference Between Daemon Threads and User Threads In Java

Java 8Object Oriented ProgrammingProgramming

As we know java is a language that supports multi threading and on the basis of nature threads in java are classified into two types Daemon thread and User thread.

The following are the important differences between Daemon Threads and User Threads.

Sr. No.KeyDaemon ThreadsUser Threads
1NatureDaemon thread is low in priority i.e JVM does not care much about these types of threads.User threads are recognized as high priority thread i.e. JVM will wait for any active user thread to get completed.
2CPU availabilityIt is not guaranteed that Daemon thread always gets CPU usage whenever it requires due to its low priority.User thread always gets preference in getting CPU usage because of its higher priority.
3CreationDaemon threads are executed in the background state so generally named as background threads.While user thread is usually created by the application for executing some tasks concurrently.
4Execution GroundDaemon threads are executed in the background state so generally named as background threads.User threads are called foreground threads on another hand.
5LifeCycleDaemon thread has no set lifecycle however they are totally dependent on user threads.User threads have a specific lifecycle as any other general thread does and its life is independent of any other thread.

Example of Daemon thread vs User threads

 Live Demo

JavaTester.java

class JavaTester extends Thread {
   @Override
   public void run(){
      System.out.println("User Thread or Non-Daemon Thread");
   }
}
public class MainThread {
   public static void main(String[] args){
      JavaTester mt = new JavaTester();
      mt.start();
      System.out.println("Main Thread");
      System.out.println("Is " + mt.getName() + " a Daemon Thread: "+ mt.isDaemon());
      System.out.println("Is " + Thread.currentThread().getName() + " a Daemon Thread: " +  Thread.currentThread().isDaemon());
   }
}

Output

Main Thread
Is Thread-0 a Daemon Thread: false
Is main a Daemon Thread: false
User Thread or Non-Daemon Thread
raja
Published on 18-Sep-2019 12:06:53
Advertisements