ThreadPool线程池的创建

本文详细介绍了如何在SpringBoot项目中配置线程池,包括application.properties的参数设置,@EnableAsync注解的使用,ThreadPoolProperties和ThreadPoolTaskExecutor的配置,以及如何通过异步API调用。通过实例展示了如何确保线程池的有效管理和任务调度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

springboot项目配置

1、application.properties 线程池基本属性值配置:

threadpool.corePoolSize=10
threadpool.maxPoolSize=50
threadpool.queueCapacity=300
threadpool.keepAliveSeconds=1000
threadpool.threadNamePrefix="elk-"

2、Application启动类上面加开启异步注解@EnableAsync

@SpringBootApplication
@EnableAsync
public class ElkApplication {
    public static void main(String[] args) {
        SpringApplication.run(ElkApplication.class, args);
    }
}

3、ThreadPoolProperties属性值配置

@Data
@Component
@ConfigurationProperties(prefix = "threadpool")
public class ThreadPoolProperties {
    private Integer corePoolSize;
    private Integer maxPoolSize;
    private Integer queueCapacity;
    private Integer keepAliveSeconds;
    private String threadNamePrefix;
}

4、ThreadPoolTaskConfig线程池创建配置

@Configuration
public class ThreadPoolTaskConfig {
    @Autowired
    private ThreadPoolProperties threadPoolProperties;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());

        // 线程池对拒绝任务的处理策略 - 调用的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }
}

5、异步线程调用

    @GetMapping
    public void get() {
        System.out.println("1");
        threadPoolTaskExecutor.execute(()->
                log.info("执行线程:{}",Thread.currentThread().getName())
        );
        for (int i = 0; i < 10; i++) {
            System.out.println("2");
        }
        threadPoolTaskExecutor.execute(()->
                log.info("执行线程:{}",Thread.currentThread().getName())
        );
        System.out.println("3");
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值