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

场景

在使用 JUnit 单元测试对多线程测试时子线程没有执行,测试非多线程问题则可以正常执行。

原因

JUnit 运行时会在主线程直接完成后调用 System.exit 退出,不会等待各个线程运行结束。

解决方案

死循环

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

    for (int i = 1; i  {
            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()// 线程等待队列
    );
    CountDownLatch countDownlatch = new CountDownLatch(threadNum);//使用计数器

    for (int i = 1; i  {
            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();

}

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/467c525c6f.html