junit 主线程结束之后会直接结束虚拟机

2022-09-13  本文已影响0人  饱饱想要的灵感

如下代码, 打印语句无法正常执行

    @Test
    public void executorTest() {
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(()-> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("%s---睡了3秒钟\n", Thread.currentThread().getName());
        });
    }

可在System.exit()方法中断点, 然后会发现, junit主线程结束后直接调用了System.exit(0)

    public static void exit(int status) {
        Runtime.getRuntime().exit(status);
    }

因此, 如果多线程代码要用junit测试, 需保证主线程的执行时间比子线程长, 比如:

    @Test
    public void executorTest() throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(()-> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.printf("%s---睡了3秒钟\n", Thread.currentThread().getName());
        });

        Thread.sleep(10_000);
    }

或者使用main()方法直截了当

上一篇 下一篇

猜你喜欢

热点阅读