当前位置: 移动技术网 > IT编程>开发语言>Java > Junit 多线程测试

Junit 多线程测试

2019年08月22日  | 移动技术网IT编程  | 我要评论

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){}
    }
}

曲线救国

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网