Junit 多线程测试

Junit不能用来做多线程测试,因为Junit不支持多线程

Junit的TestRunner的main方法源码

    public static void main(String args[]) {
        TestRunner aTestRunner = new TestRunner();
        try {
            TestResult r = aTestRunner.start(args);
            if (!r.wasSuccessful()) {
                System.exit(FAILURE_EXIT);
            }
            System.exit(SUCCESS_EXIT);
        } catch (Exception e) {
            System.err.println(e.getMessage());
            System.exit(EXCEPTION_EXIT);
        }
    }

从源码可以看出来,Junit是监控的main线程,一旦main线程执行结束就直接exit了,根本不管子线程的死活。

知道了Junit的原理,我觉得可以尝试实现一下支持多线程,不就是让main线程不要退出嘛,简单。

public class MyTest {
    private static final int LEN = 20;
    //存储线程数量Active Thread Count
    private static final int ATC = Thread.activeCount();
    @Test
    public void testCase(){
        List<String> list = new ArrayList<>();
        for(int i = 0;i<LEN;i++){
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName());
            },"T"+String.valueOf(i)).start();
        }
        //只要线程数量比ATC多就说明,自己创建的线程还有没执行完的。
        while(Thread.activeCount() > ATC){}
    }
}

曲线救国

猜你喜欢

转载自www.cnblogs.com/macho8080/p/11393847.html