Java Thread Tutorial - Java Thread Demon








A thread can be a daemon thread or a user thread.

A daemon thread is a service provider thread.

When JVM detects that all threads in an application are only daemon threads, it exits the application.

We can make a thread a daemon thread by using the setDaemon() method by passing true as its argument.

We must call the setDaemon() method of a thread before starting the thread. Otherwise, an java.lang. IllegalThreadStateException is thrown.

We can use the isDaemon() method to check if a thread is a daemon thread.

When a thread is created, its daemon property is the same as the thread that creates it.

Example

The following code creates a thread and sets the thread as a daemon thread.

public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(Main::print);
    t.setDaemon(true);/*w  ww.j  ava 2  s . com*/
    t.start();
    System.out.println("Exiting main  method");
  }

  public static void print() {
    int counter = 1;
    while (true) {
      try {
        System.out.println("Counter:" + counter++);
        Thread.sleep(2000); // sleep for 2 seconds
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

The code above generates the following result.





Example 2

The following code sets the thread as a non-daemon thread. Since this program has a non-daemon thread, the JVM will keep running the application, even after the main() method finishes.

You will have to stop this application forcibly because the thread runs in an infinite loop.

public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(Main::print);
    t.setDaemon(false);//ww w  . j  av a2s  . c o m
    t.start();
    System.out.println("Exiting main  method");
  }
  public static void print() {
    int counter = 1;
    while (true) {
      try {
        System.out.println("Counter:" + counter++);
        Thread.sleep(2000); // sleep for 2 seconds
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

The code above generates the following result.