美文网首页测试框架工作生活Test
多线程之单元测试(Junit)

多线程之单元测试(Junit)

作者: Unyielding_L | 来源:发表于2018-07-24 19:18 被阅读1905次

    多线程测试服务

    • 1.新建一个核心数为100 的线程池

    ExecutorService service = Executors.newFixedThreadPool(100);
    
    • 2.执行一个阻塞不大的任务

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

    测试发现什么都没有打印

    查阅资料发现

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

    解决方法

      1. 使用在主线程中使用join 等待子线程执行完
    try {
                Thread.currentThread().join();
            } catch (InterruptedException e) {
                e.printStackTrace();
    
      }
    
    • 结果


      Join方法.png
      1. 使用CountDownLatch 等待
    • 2.1 任务类RunableTask
    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();
            }
        }
    }
    
    • 2.2 测试方法
    @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地址

    相关文章

      网友评论

        本文标题:多线程之单元测试(Junit)

        本文链接:https://www.haomeiwen.com/subject/ngtymftx.html