Spring的线程池ThreadPoolTaskExecutor

30 篇文章 3 订阅
6 篇文章 0 订阅

我们先瞄一眼源码:

corePoolSize = 1; int maxPoolSize = 2147483647; 这...不适合我,我要自己覆盖怎么做?
**
 * @author Lxq
 * @version 1.0
 * @date 2020/10/15 15:21
 */
@Configurable
public class ThreadPoolTaskExecutorConfig {

    @Bean
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor  = new ThreadPoolTaskExecutor();
        //获取到服务器的cpu内核
        int cpus = Runtime.getRuntime().availableProcessors();
        // 核心线程数
        executor .setCorePoolSize(cpus * 2);
        // 最大的线程数
        executor.setMaxPoolSize(1000);
        // 阻塞队列的长度
        executor.setQueueCapacity(1000);
        // 线程的空闲时间
        executor.setKeepAliveSeconds(5000);
        // 线程前缀名称
        executor.setThreadNamePrefix("task-asyn");
        //配置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }

    @Bean
    public Executor asyncServiceExecutor() {
        //使用VisiableThreadPoolTaskExecutor
        ThreadPoolTaskExecutor executor = new VisiableThreadPoolTaskExecutor();
        //获取到服务器的cpu内核
        int cpus = Runtime.getRuntime().availableProcessors();
        //配置核心线程数
        executor.setCorePoolSize(cpus * 2);
        //配置最大线程数
        executor.setMaxPoolSize(1000);
        //配置队列大小
        executor.setQueueCapacity(99999);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-service-");
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

  譬如,我们跑多线程的时候先知道目前执行的线程池的情况是什么情况,完成了多少,活跃的多少,队列的中有多少怎么办?



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.concurrent.ListenableFuture;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author Lxq
 * @version 1.0
 * @date 2020/10/15 12:21
 */
public class VisiableThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
    
    private static final Logger logger = LoggerFactory.getLogger(VisiableThreadPoolTaskExecutor.class);

    private void showThreadPoolInfo(String prefix){
        ThreadPoolExecutor threadPoolExecutor = getThreadPoolExecutor();
        if(null==threadPoolExecutor){
            return;
        }
        logger.info("{}, {},taskCount [{}], completedTaskCount [{}], activeCount [{}], queueSize [{}]",
                this.getThreadNamePrefix(),
                prefix,
                threadPoolExecutor.getTaskCount(),
                threadPoolExecutor.getCompletedTaskCount(),
                threadPoolExecutor.getActiveCount(),
                threadPoolExecutor.getQueue().size());
    }

    @Override
    public void execute(Runnable task) {
        showThreadPoolInfo("1. do execute");
        super.execute(task);
    }

    @Override
    public void execute(Runnable task, long startTimeout) {
        showThreadPoolInfo("2. do execute");
        super.execute(task, startTimeout);
    }

    @Override
    public Future<?> submit(Runnable task) {
        showThreadPoolInfo("1. do submit");
        return super.submit(task);
    }

    @Override
    public <T> Future<T> submit(Callable<T> task) {
        showThreadPoolInfo("2. do submit");
        return super.submit(task);
    }

    @Override
    public ListenableFuture<?> submitListenable(Runnable task) {
        showThreadPoolInfo("1. do submitListenable");
        return super.submitListenable(task);
    }

    @Override
    public <T> ListenableFuture<T> submitListenable(Callable<T> task) {
        showThreadPoolInfo("2. do submitListenable");
        return super.submitListenable(task);
    }
}


继承ThreadPoolTaskExecutor在执行任务前,查看当前线程池的情况,ojbk

别光说,操作他一波

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test12 {

    @Autowired
    @Qualifier("asyncServiceExecutor")
    private Executor taskExecutor;

    @Test
    public void main111() throws InterruptedException {
        long startTime = System.currentTimeMillis();
        System.out.println("==========开始时间==============================");
        CountDownLatch countDownLatch = new CountDownLatch(1000);

        List<Integer> list = new ArrayList<>();
        List<Integer> list1 = Collections.synchronizedList(list);
        for (int i = 0; i < 1000 ; i++) {
            int finalI = i;
            taskExecutor.execute(()->{
                try {
                    list1.add(finalI);
                    Thread.sleep(5);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();

        System.out.println("==========用时"+(System.currentTimeMillis()-startTime)+"==============================");
        System.out.println(1);
    }


}

 这里可以看到线程池中完成的线程数,活跃的线程数,阻塞队列的长度。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值