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);
/
/每次计数减⼀
}
}