Thread-daemon thread and non-daemon thread

Multithreading-daemon thread and non-daemon thread

What is a daemon thread?

Non-daemon threads are easy to understand, they are the threads running in the front end of the program. I personally understand them as threads that are often used to handle active transactions.
Daemon thread: As the name implies, a thread used to guard transactions. It mainly runs on the back end of the program. The most representative example of the GC thread is the daemon thread.

Features of daemon threads

  • The daemon thread runs at the back end of the program and ends with the end of the non-daemon thread. That is to say, the daemon thread will be terminated when there is no daemon thread in the program. It can be understood that if there is no guardian in the program, the guardian thread will also be terminated.
  • The daemon thread can be set by the setDaemon method in Thread, but it must be set before the start method.
  • The daemon thread should try not to call system resources, such as files, databases, etc. Because it may be interrupted at any time.
Implement the daemon thread, and verify that the daemon thread is also interrupted when the non-daemon thread ends.
/**
 * Created by 一只会飞的猪 on 2021/3/8.
 */

// 守护线程
public class DaemonThread implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i <100000; i++) {
              System.out.println(Thread.currentThread().getName()+"我是守护线程,我正在运行");
        }
    }
}


// 非守护线程
class OtherThread implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i <10; i++) {
            System.out.println(Thread.currentThread().getName()+"我是非守护线程,我正在运行");
        }
    }
}


class StartMain{
    public static void main(String[] args) {
           // 启动非守护线程
           new Thread(new OtherThread()).start();
           // 设置守护线程
           Thread threaddaomon = new Thread(new DaemonThread());
           threaddaomon.setDaemon(true);
           // 启动线程
            threaddaomon.start();
    }

Result: It
Insert picture description here
can be seen that although my daemon thread has operated 100,000 times, the daemon thread did not continue execution after the non-daemon thread ended.

Guess you like

Origin blog.csdn.net/qq_31142237/article/details/114551689