java项目怎么多线程跑单元测试,ide是intellij?

如题,java项目怎么多线程跑单元测试,ide是intellij? 是用junit还是testng啊, 参数该怎么设置呢?还有什么好的方法并行跑unit test case呢?

阅读 7k
2 个回答

用 maven 的 surefire 插件可以实现

        <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.20.1</version>
                <configuration>
                    <parallel>classes</parallel>                
                    <threadCount>5</threadCount>
                </configuration>
      </plugin>          

多线程跑单测一般碰到的问题就是主线程执行完之后子线程还在运行,但是单测就结束了拿不到结果。

所以本质上只需要子线程执行完毕之后告诉主线程,再这之前主线程一直等待即可。

如果是线程池可以这样:

for (int i = 0; i < 50; i++) {
    executorServicePool.execute(new Worker(i));
}

executorServicePool.shutdown();
while (!executorServicePool.awaitTermination(1, TimeUnit.SECONDS)) {
    logger.info("worker running");
}
logger.info("worker over");

每隔一秒钟检查一次线程池里的任务执行完没有,没有执行完就阻塞主线程。

CountDownLatch 这样的并发工具也不错。

private static void countDownLatch() throws Exception{
    int thread = 3 ;
    long start = System.currentTimeMillis();
    final CountDownLatch countDown = new CountDownLatch(thread);
    for (int i= 0 ;i<thread ; i++){
        new Thread(new Runnable() {
            @Override
            public void run() {
                LOGGER.info("thread run");
                try {
                    Thread.sleep(2000);
                    countDown.countDown();
                    LOGGER.info("thread end");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    countDown.await();
    long stop = System.currentTimeMillis();
    LOGGER.info("main over total time={}",stop-start);
}

当然 join 的方式也是可以的。

private static void join() throws InterruptedException {
    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("running");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }) ;
    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            LOGGER.info("running2");
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }) ;
    t1.start();
    t2.start();
    //等待线程1终止
    t1.join();
    //等待线程2终止
    t2.join();
    LOGGER.info("main over");
}

更多内容可以查看:

深入理解线程间通信

推荐问题