Junit 使用 CountDownLatch 多线程测试

13 篇文章 1 订阅
6 篇文章 0 订阅
package com.lgq.demo;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.ActiveProfiles;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 多线程测试
 *
 * @Author: guanqin_li
 * @Date: 2021-02-18 10:39
 */
@SpringBootTest
@ActiveProfiles("dev")
public class ThreadTest {
    @Test
    public void test() throws InterruptedException {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("thread-pool-");
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(300);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        // 任务总数
        final int total = 20;
        CountDownLatch countDownLatch = new CountDownLatch(total);
        System.out.println("=========start=======");
        for (int i = 0; i < total; i++) {
            executor.execute(() -> {
                try {
                    //TODO 业务处理
                    System.out.println(Thread.currentThread().getName() + "|" + countDownLatch.getCount());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
                    countDownLatch.countDown();
                }
            });
        }
        // 所有线程countDown()都执行之后才会释放当前线程,程序才能继续往后执行
        countDownLatch.await();
        //关闭线程池
        executor.shutdown();
        System.out.println("=========finished=======");
    }
}

运行结果:

2021-02-18 10:50:07.000  INFO 115072 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService
=========start=======
thread-pool-1|20
thread-pool-1|19
thread-pool-1|18
thread-pool-1|17
thread-pool-1|16
thread-pool-1|15
thread-pool-1|14
thread-pool-1|13
thread-pool-1|12
thread-pool-1|11
thread-pool-1|10
thread-pool-1|9
thread-pool-1|8
thread-pool-1|7
thread-pool-1|6
thread-pool-1|5
thread-pool-2|4
thread-pool-3|4
thread-pool-4|2
thread-pool-5|1
2021-02-18 10:50:07.006  INFO 115072 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService
=========finished=======

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值