测试框架工作生活Test

多线程之单元测试(Junit)

2018-07-24  本文已影响1905人  Unyielding_L

多线程测试服务

ExecutorService service = Executors.newFixedThreadPool(100);
service.execute(()->{
try {
    for (int i =0; i <100; i++) {
            Thread.sleep(100);
            System.out.println("我阻塞了100ms");
        }
   }catch (InterruptedException e) {
    e.printStackTrace();
    }
});

测试发现什么都没有打印

查阅资料发现

junit 单元测试当主线程执行完毕,主线程会关闭,并且关闭子线程

解决方法

try {
            Thread.currentThread().join();
        } catch (InterruptedException e) {
            e.printStackTrace();

  }
public class RunableTask implements Runnable {
    private CountDownLatch countDownLatch;
    public RunableTask(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(100);
            System.out.println("我阻塞了100ms");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            countDownLatch.countDown();
        }
    }
}
@Test
    public void runCountDown() {
        for (int i = 0; i < 100; i++) {
            service.execute(new RunableTask(countDownLatch));
        }
        try {
            countDownLatch.await();
            log.info("执行成功");
        } catch (InterruptedException e) {
            e.printStackTrace();
            log.log(Level.WARNING,e,()->"抛出中断异常");
        }
    }

结果


CoutDownLautch 起效果.png

当然还可以让主线程睡眠来等待子线程
github地址

上一篇下一篇

猜你喜欢

热点阅读