JUC - user thread and daemon thread

Java threads are divided into user threads and daemon threads

Generally, there is no special instructions for configuration, and the default is user thread

User thread: It is the working thread of the system, which will complete the business operations that this program needs to complete.

Daemon thread: It is a special thread that serves other threads and completes some systemic services in the background, such as garbage collection threads.

As a service thread, the daemon thread does not need to continue running without a service object. 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 if there are only daemon threads left in the system, the java virtual machine will automatically exit.

Judging whether the thread is a user thread or a daemon thread has an attribute called isDaemon

true means it is a daemon thread

false means it is a user thread

public class Test2 {
    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"  "+Thread.currentThread().isDaemon());
        },"t1").start();
    }
}

 The result is false, indicating that it is not a daemon thread, that is, a user thread

import java.util.concurrent.TimeUnit;

public class Test2 {
    public static void main(String[] args) {
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"  "+Thread.currentThread().isDaemon());
            while (true){

            }
        },"t1").start();

        //暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName()+"   end");
    }


}

 It can be seen that the thread t1 is not over, but the main thread has been executed, but the program has not exited at this time, indicating that the user threads do not affect each other.

But when we set t1 as daemon thread

 

 When the main thread ends, the program exits.

Guess you like

Origin blog.csdn.net/a2285786446/article/details/131536715