JUC learning - user threads and daemon threads

1, User thread and daemon thread

1. Guardian thread & understanding of user thread

Daemon thread is a special thread that silently completes some systematic services in the background, such as garbage collection thread and JIT thread.

The corresponding is the user thread, which can be understood as the working thread of the system. It will complete the business operations required by the program.

If all user threads end, it means that the business operations that the program needs to complete have ended, and the system can exit.

So when there are only daemons left in the system, the java virtual opportunity exits automatically.

java threads are divided into user threads and daemon threads. If the daemon attribute of a thread is true, it means daemon threads and false means user threads.

Let's look at some features of daemon threads.

2. When the program has only daemon thread, the system will exit automatically

public class DaemonDemo {
    public static class T1 extends Thread {
        public T1(String name) {
            super(name);
        }
        
        @Override
        public void run() {
            System.out.println(this.getName() + "Start execution," + (this.isDaemon() ? "I'm a daemon" : "I'm a user thread"));
            while (true) {}
        }
    }
    
    public static void main(String[] args) {
        T1 t1 = new T1("Child thread 1");
        t1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Main thread end");
    }
}

Run the above code and the results are as follows:

You can see that the main thread has ended, but the program cannot exit. Reason: sub thread 1 is a user thread. There is an internal dead loop. It is always running and cannot end.

Look at the following code:

public class DaemonDemoTwo {
    public static class T1 extends Thread {
        public T1(String name) {
            super(name);
        }
        @Override
        public void run() {
            System.out.println(this.getName() + "Start execution," + (this.isDaemon() ? "I'm a daemon" : "I'm a user thread"));
            while (true) ;
        }
    }
    
    public static void main(String[] args) {
        T1 t1 = new T1("Child thread 1");
        t1.setDaemon(true);
        t1.start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Main thread end");
    }
}

Run the above code and the results are as follows:

From the above results, we can see that the program can end normally. In the code, t1.setDaemon(true) is passed; Set the T1 thread as the daemon thread. After the main thread where the main method is located is executed, the program exits.

Conclusion: when all user threads in the program are executed, the system will exit automatically regardless of whether the daemon thread ends or not.

3. Setting the daemon thread needs to be done before the start() method

public class DaemonDemoThree {
    
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        t1.start();
        t1.setDaemon(true);
    }
    
}

You can see t1.setDaemon(true); It is executed after the start() method of t1, and an exception will be reported. The running results are as follows:

4. Default value for thread daemon

Let's take a look at the source code of Thread creation, which is located in the init() method of Thread class:

Thread parent = currentThread();
this.daemon = parent.isDaemon();

The default value of daemon is the daemon of the parent thread, that is, if the parent thread is a user thread, the child thread is also the user site by default. If the parent thread is a daemon thread, the child thread is also a daemon thread by default.

Example code:

public class DaemonDemoFour {
    
    public static class T1 extends Thread {
        public T1(String name) {
            super(name);
        }
        @Override
        public void run() {
            System.out.println(this.getName() + ".daemon:" + this.isDaemon());
        }
    }
    
    public static void main(String[] args) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + ".daemon:" + Thread.currentThread().isDaemon());
        // Create and start t1 thread
        T1 t1 = new T1("t1");
        t1.start();
        
        Thread t2 = new Thread() {
            @Override
            public void run() {
                System.out.println(this.getName() + ".daemon:" + this.isDaemon());
                // Create and start the t3 thread within the t2 thread
                T1 t3 = new T1("t3");
                t3.start();
            }
        };
        
        t2.setName("t2");
        // Set t2 thread as daemon thread
        t2.setDaemon(true);
        t2.start();
        TimeUnit.SECONDS.sleep(2);
    }
}

Run code, output:

main.daemon:false
t1.daemon:false
t2.daemon:true
t3.daemon:true
  • T1 is created by the main thread (the thread where the main method is located). The main thread is the parent thread of T1, so t1.daemon is false, indicating that T1 is a user thread.

  • T2 thread called setDaemon(true); Set it as a daemon thread. t3 is created by T2, so the default thread type of t3 is the same as T2, and t2.daemon is true.

5. Summary

  1. Threads in java are divided into user threads and daemon threads
  2. After all user threads in the program are finished, the java virtual machine will exit automatically no matter what state the daemon thread is in
  3. Call the thread's instance method setDaemon() to set whether the thread is a daemon thread
  4. The setDaemon() method must be called before the start() method of the thread. It will report exceptions after the call and will not work.
  5. The daemon default value of a thread is the same as its parent thread

Article reference: http://www.itsoku.com/ Bloggers think the content of this article is very good. If you are interested, you can learn about it.

Tags: Java Back-end Multithreading JUC

Posted on Thu, 25 Nov 2021 15:27:39 -0500 by ben2468