栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()方法一定要创建新的线程,然后从中写逻辑

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/972428.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号