Spring Boot中的线程问题

代码如下:

@SpringBootApplication
@Controller
public class DemoApplication {

    public static void main(String[] args) {

        SpringApplication.run(DemoApplication.class, args);

        Thread thread = new Thread(() -> {
        });
        System.out.println("Thead 1 - > " + thread.isDaemon());
    }


    @GetMapping("/")
    public void test() {
        Thread thread = new Thread(() -> {
        });
        System.out.println("Thead 2 - > " + thread.isDaemon());
    }

}

运行结果如图:


如上图所示,Java中创建线程默认都是用户线程。但是为什么在GetMapping中创建的线程却是守护线程?

线程类的init方法中有一句代码

 this.daemon = parent.isDaemon();

应该是当前线程,如果没有设置,则 daemon 继承自父线程。

你在Main函数中创建线程,那么父线程就是 Main 主线程。
你在GetMapping中创建线程,那么父线程是 处理请求的线程池 中的线程。(可能是线程池中的线程,就是个守护线程,所以。它创建的线程。默认也是守护线程。)

1 个赞

多谢 前辈:grinning:

1 个赞