Daemon thread in Java


A Daemon thread is a background service thread which runs as a low priority thread and performs background operations like garbage collection. JVM exits if only daemon threads are remaining.

The setDaemon() method of the Thread class is used to mark/set a particular thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be called before the thread is started.

Example

Live Demo

class adminThread extends Thread {
   adminThread() {
      setDaemon(false);
   }
   public void run() {
      boolean d = isDaemon();
      System.out.println("daemon = " + d);
   }
}

public class Tester {
   public static void main(String[] args) throws Exception {
      Thread thread = new adminThread();
      System.out.println("thread = " + thread.currentThread());
      thread.setDaemon(false);
      thread.start();
   }
}

Output

thread = Thread[main,5,main]
daemon = false
raja
Published on 25-Jul-2018 16:22:55
Advertisements