Difference between a daemon thread and a low priority thread

前端 未结 4 1120
忘了有多久
忘了有多久 2020-12-06 11:56

Recently I was asked a question:

We\'ve got the setPriority() method to set a thread for low priority. Then why do we need a daemon thr

4条回答
  •  离开以前
    2020-12-06 12:43

    An example of

    1. JVM shutting down when low priority thread completes. Despite Daemon threads still running
    2. ALSO, shows that thread created by a daemon thread automatically becomes a daemon thread

      package junk.daemon_thread_example;
      
      class DeamonThreadPlus implements Runnable{
          String id;
          boolean createChild;
      
          public DeamonThreadPlus(String id, boolean createChild){
              this.id = id;
              this.createChild = createChild;
          }
      
          @Override
          public void run() {
              // Parent daemon thread creates child daemon thread by default
              if (createChild)
                  new Thread(new DeamonThreadPlus("DaemonChild", false)).start();
      
              // This thread never self-completes (only terminates when process dies)
              while (true){
                  try {
                      Thread.sleep(1);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  System.out.println("Daemon " 
                          + Thread.currentThread().isDaemon()
                          + " id = " + id);
                  }
          }
      }
      
      class UThread implements Runnable{
      
          @Override
          public void run() {
              System.out.println("User thread start");
              try {
                  Thread.sleep(5);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }
              System.out.println("User thread end (program exits)");
          }
      }
      
      public class Caller{
      
          public static void main(String[] args) {
              Thread dt = new Thread( new DeamonThreadPlus("Daemon", true));
              dt.setDaemon(true);
              dt.start();
      
              Thread ut = new Thread(new UThread());
              ut.setPriority(Thread.MIN_PRIORITY);
              ut.start(); 
          }
      
      }
      

      The output is: User thread start
      Daemon true id = Daemon
      Daemon true id = DaemonChild
      Daemon true id = Daemon
      Daemon true id = DaemonChild
      Daemon true id = Daemon
      Daemon true id = DaemonChild
      Daemon true id = Daemon
      Daemon true id = DaemonChild
      User thread end (program exits)
      Daemon true id = DaemonChild
      Daemon true id = Daemon

提交回复
热议问题