Java - Thread Thread Demon

Introduction

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.

You can set a thread a daemon thread by using the setDaemon() method.

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

isDaemon() method checks if a thread is a daemon thread.

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

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

The thread prints an integer and sleeps for some time in an infinite loop.

Since thread t is a daemon thread, the JVM will terminate the application when the main() method is finished executing.

Demo

public class Main {
  public static void main(String[] args) {
    Thread t = new Thread(Main::print);
    t.setDaemon(true);//from  ww  w .j  av a  2 s. co 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();
      }
    }
  }
}

Result

Related Topics