SpringBoot创建自定义线程池

SpringBoot创建自定义线程池,第1张

SpringBoot创建自定义线程

使用Java代码结合使用@Configuration进行配置

package com.gome.lmis.gop.common;

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

import java.util.concurrent.ThreadPoolExecutor;


@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
    

    
    private static final int corePoolSize = 20;

    
    private static final int maxPoolSize = 100;

    
    private static final int keepAliveTime = 10;

    
    private static final int queueCapacity = 200;

    private static final String threadNamePrefix = "Async-Service-";

    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveTime);
        threadPoolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        //线程池对拒绝任务的处理策略
        //CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化 必须初始化,否则报 ThreadPoolTaskExecutor not initialized
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }


}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5684198.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存