What method is used to create a daemon thread in Java?


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:

import java.lang.*;

class adminThread extends Thread {
   adminThread() {
      setDaemon(false);
   }

   public void run() {
      boolean d = isDaemon();
      System.out.println("daemon = " + d);
   }
}

public class ThreadDemo {
   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 12-Jan-2018 12:22:35
Advertisements