Junit在多线程测试时的坑

2023-12-29 17:48:28

Junit单元测试主线程退出,子线程也会退出

    @Test
    public void test() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+":finish");
        }, "t1");
        t1.start(); 
    }

可以看到什么都不会打印,如果给主线程也加上sleep,那就可以了

    @Test
    public void test() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+":finish");
        }, "t1");
        t1.start();
        TimeUnit.SECONDS.sleep(6);
    }

文章来源:https://blog.csdn.net/qq_62767608/article/details/135295052
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。