Junit在多线程测试时的坑

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(); 
    }

Junit在多线程测试时的坑_第1张图片

可以看到什么都不会打印,如果给主线程也加上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);
    }

你可能感兴趣的:(项目报错,junit,java)