天天看点

JUnit 单元测试多线程测试解决方法

场景

原因

解决方案

死循环

@Test
public void demo() {
    int threadNum = 10;
    // 初始化线程池
    ExecutorService executorService = new ThreadPoolExecutor(threadNum,// 核心线程池大小
            100,// 最大线程池大小
            60L,// 线程最大空闲时间;线程空闲60s后自动结束
            TimeUnit.MILLISECONDS,// 时间单位
            new LinkedBlockingQueue<Runnable>()// 线程等待队列
    );

    for (int i = 1; i <= threadNum; i++) {
        executorService.execute(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        });


    }

    while (true) {

    }

}      

CountDownLatch

@Test
public void demo() {
    int threadNum = 10;
    // 初始化线程池
    ExecutorService executorService = new ThreadPoolExecutor(threadNum,// 核心线程池大小
            100,// 最大线程池大小
            60L,// 线程最大空闲时间;线程空闲60s后自动结束
            TimeUnit.MILLISECONDS,// 时间单位
            new LinkedBlockingQueue<Runnable>()// 线程等待队列
    );
    CountDownLatch countDownlatch = new CountDownLatch(threadNum);//使用计数器

    for (int i = 1; i <= threadNum; i++) {
        executorService.execute(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());

            // 每次计数减一,很关键, 否则await无法释放
            countDownlatch.countDown();
        });

    }

    try {
        // 当计数为0时结束阻塞,所有线程countDown()都执行之后才会释放当前线程,程序才能继续往后执行
        countDownlatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    //关闭线程池
    executorService.shutdown();

}