Java为什么启动类实现了CommandLineRunner接口后需要创建一个新的线程

为何springboot启动类实现了CommandLineRunner.run()后需要创建新的线程

1.先写个controller类方便请求测试
http://localhost:8080/test/getRequest

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("getRequest")
    public String enums() {
        System.out.println("收到请求...");
        return "success";
    }
}

2.在启动类实现CommandLineRunner接口,此时没有创建新的线程,直接重写了CommandLineRunner中的run()方法.

public class Demo01Application implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(Demo01Application.class, args);
    }

    @Override
    public void run(String... args) {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("2s.....   i = " + i);
            if (i == 3) throw new RuntimeException("i == 3 runtimeException...");
        }
    }
}

启动测试…
在这里插入图片描述
如图显示,此时项目日志显示启动失败
尝试访问
在这里插入图片描述
并不行…

---------------分割线-----------------

此时采用创建线程方式再次测试…

public class Demo01Application implements CommandLineRunner {
    public static void main(String[] args) {
        SpringApplication.run(Demo01Application.class, args);
    }

    @Override
    public void run(String... args) {
        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 5; i++) {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("2s.....   i = " + i);
                    if (i == 3) throw new RuntimeException("i == 3 runtimeException...");
                }
            }
        }.start();
    }
}

在这里插入图片描述
如图显示启动成功…
再次尝试访问
在这里插入图片描述
访问成功


这是因为如果不采用创建线程的方式实现CommandLineRunner的run()方法.项目主线程需要等待CommandLineRunner.run()成功执行完成之后才能完成真正的启动.如果此时CommandLineRunner.run()报错.将导致整个项目启动失败.
采用创建线程的方式启动即使报错了,也是这个单个线程报错.不影响整个项目的启动
所以,当实现了CommandLineRunner.run()方法一定要创建新的线程,然后从中写逻辑

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

s_wei_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值