Java daemon thread and its application

Java threads are divided into two types: User Thread and Daemon Thread.

Usually we usually use user threads, but daemon threads are rarely used, only in some specific scenarios. The daemon thread is generally used to serve other threads. For example, the garbage collection of the JVM is a daemon thread that collects garbage objects for other threads.

The characteristics of the guardian thread: the life cycle depends on other threads. When the last user thread ends, the guardian thread will be forced to end. I used to like to read fantasy novels. Is it very similar to the master-servant agreement in the novel? To die

Code

		System.out.println("主线程运行开始");
        Thread thread = new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                while (true) {
    
    
                    System.out.println("用户线程运行中");
                    try {
    
    
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
        System.out.println("主线程运行结束");

result

主线程运行开始
主线程运行结束
用户线程运行中
用户线程运行中
用户线程运行中
用户线程运行中
用户线程运行中
用户线程运行中

From the execution result of the above code, after the main thread ends, but the user thread is still running, the JVM cannot exit

Code

		System.out.println("主线程运行开始");
        Thread thread=new Thread(new Runnable() {
    
    
            @Override
            public void run() {
    
    
                while (true){
    
    
                    System.out.println("守护线程运行中");
                    try {
    
    
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
        System.out.println("主线程运行结束");

result

主线程运行开始
守护线程运行中
主线程运行结束

But if it is a daemon thread, after the main thread ends, the daemon thread will be forced to end, which is very suitable for performing some background tasks

Practical application scenario: I remember when I first worked in 18 years, I was responsible for the development of an elderly care platform, docking a mattress, the elderly’s sleep heart rate, blood pressure, and sleep status will be displayed on the large screen, data collection is real-time, data collection is through a while The infinite loop plus sokect is used to obtain the daemon thread, because after the main program ends, the data collection is meaningless

Guess you like

Origin blog.csdn.net/qq_38306425/article/details/109159772