Springboot自定义线程池ThreadPoolTaskExecutor

2023-12-13 18:04:06

Java提供了几种线程池默认创建方式,但一般我们在项目里使用线程池,都是自定义核心线程数、最大线程数、阻塞队列大小、拒绝策略等等一系列参数。今天正好使用到了,做个记录

package org.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池
 * @Author
 * @Date:2023/12/6 15:44
 * @Version:1.0
 * @Desc
 */
@Configuration
public class ThreadPoolConfig {

    @Bean("myThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor MyThreadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //获取cpu核心数
        final int cpu = Runtime.getRuntime().availableProcessors();
        //设置核心线程池数
        final int corePoolSize = cpu + 1;
        //设置最大线程数量
        final int maximumPoolSize = cpu * 2 + 1;
        //设置阻塞队列
        final int maxQueueNum = 1 << 7;
        //核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maximumPoolSize);
        //队列容量
        executor.setQueueCapacity(maxQueueNum);
        //活跃时间
        executor.setKeepAliveSeconds(60);
        //线程名字前缀
        executor.setThreadNamePrefix("cent_direct_print_push_");
        // 拒绝策略
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.AbortPolicy()
        );
        executor.initialize();
        return executor;
    }

}

文章来源:https://blog.csdn.net/qq_30434271/article/details/134837297
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。