Java thread Daemon usage example

  • 2020-04-01 04:00:15
  • OfStack

This article illustrates the use of Java threads as daemons. Share with you for your reference. The details are as follows:

Daemon
There are two types of threads in Java: "Daemon" and "User".
The examples we've seen before are all users, and daemon threads are "generic support in the background" threads that are not part of the program body.
It's easy to think of daemon threads as being created internally by a virtual machine, and user threads as being created by themselves. This is not the case. Any thread can be a "Daemon" or "User". They are the same in almost every respect, the only difference being when the virtual machine leaves:
User threads: the Java virtual machine automatically leaves after all its non-daemon threads have left.
Daemon threads: daemon threads are used to service user threads. If there are no other user threads running, there is no serviceable object and no reason to continue.
SetDaemon (Boolean on) method can easily set the thread Daemon mode, true for Daemon mode, false for User mode. The setDaemon(Boolean on) method must be called before the thread starts, and the call generates an exception while the thread is running. The isDaemon method will test whether the thread is a daemon thread. It is worth mentioning that when you create other threads in a Daemon thread, these new threads will be Daemon threads without setting Daemon properties, and user threads will be Daemon threads as well.

Example: the familiar Java garbage collection Thread is a typical daemon Thread. When there are no more running threads in our program, the program will no longer generate garbage and the garbage collector will have nothing to do. So when the garbage collection Thread is the only Thread left on the Java virtual machine, the Java virtual machine will automatically leave.


import java.io.IOException;

public class TestMain4 extends Thread {
  public TestMain4() {
  }
  
  public void run() {
    for(int i = 1; i <= 100; i++){
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
      System.out.println(i);
    }
  }
  public static void main(String [] args){
    TestMain4 test = new TestMain4();
    test.setDaemon(true);
    test.start();
    System.out.println("isDaemon = " + test.isDaemon());
    try {
      System.in.read();
      //Accept input, cause the program to stop here, once the user input is received, the main thread ends, the daemon thread automatically ends
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}

I hope this article has been helpful to your Java programming.


Related articles: