java的junit单元测试无法进行多线程测试解决方法

更新时间:2023-05-05 19:13:41 阅读: 评论:0

java的junit单元测试⽆法进⾏多线程测试解决⽅法今天⽤junit测试代码突然发现,多线程⽆法执⾏完结果就结束程序了,后来在⽹上找了找原因:
场景⽐较特殊,⼀ 使⽤到了springboot的@test,⼆ 使⽤了线程池
1原因:
junit在运⾏时,在主线程结束后就关闭了进程,不会等待各个线程运⾏结束,junit源码
public static void main(String args[]) {
TestRunner aTestRunner = new TestRunner();
try {
TestResult r = aTestRunner.start(args);
if (!r.wasSuccessful()) {
}
} catch (Exception e) {
}
}
2解决⽅法
①要是要求不⾼,可以通过thread.sleep(),让主线程暂时休眠,其他线程运⾏完在结束
②⽐较严谨的做法,可以⽤ CountDownLatch ,具体使⽤在代码⾥有注释
//初始化⼀个发令枪对象,计数为3
private static CountDownLatch latch = new CountDownLatch(3);
@Test
public void test118(){
identifyLawBatch.handlerLaw(latch);
try {
//  当计数为0时结束阻塞
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
@Repository
public class IdentifyLawBatch {
public static void main(String[] args) {
IdentifyLawBatch ib = new IdentifyLawBatch();
}
static ExecutorService fixedThreadPool = null;
//初始化固定线程数的线程池
static {
fixedThreadPool =  wFixedThreadPool(3);
}
public void handlerLaw(CountDownLatch latch){
}
}
//识别没有版本的law任务
public class IdentifyLawRun implements Runnable {
CountDownLatch latch = null;
//传⼊查询的数据区间
Integer beginNum = 0;
Integer endNum = 0;
public IdentifyLawRun(int beginNum,int endNum,CountDownLatch latch){        this.beginNum = beginNum;
this.latch = latch;
}
@Override
public void run() {
System.out.println(beginNum);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(endNum);
/
/每次计数减⼀
}
}

本文发布于:2023-05-05 19:13:41,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/534178.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:结束   线程   版本   没有   不会   查询
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图