线程池配置

线程池配置

复制代码
/**
 * 线程池配置
 */
@Configuration
public class ThreadPoolConfig {

    /**
     * 核心线程
     */
    @Value("${threadpool.corePoolSize:10}")
    private int corePoolSize;

    /**
     * 最大线程
     */
    @Value("${threadpool.maxPoolSize:20}")
    private int maxPoolSize;

    /**
     * 队列容量
     */
    @Value("${threadpool.queueCapacity:10}")
    private int queueCapacity;

    /**
     * 保持时间
     */
    @Value("${threadpool.keepAliveSeconds:5}")
    private int keepAliveSeconds;

    /**
     * 名称前缀
     */
    @Value("${threadpool.preFix:custom-thread-}")
    private String preFix;

    @Bean("customExecutor")
    public Executor myExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        executor.setThreadNamePrefix(preFix);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.setThreadFactory(new PooledThreadFactory());
        executor.initialize();
        return executor;
    }

    public static class PooledThreadFactory implements ThreadFactory {

        @Override
        public Thread newThread(Runnable r) {
            final Thread thread = new Thread(r);
            thread.setUncaughtExceptionHandler(new ThreadPoolExceptionHandler());
            return thread;
        }
    }

    @Slf4j
    public static class ThreadPoolExceptionHandler implements UncaughtExceptionHandler {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            log.error("线程[{}]执行发生未知异常", t.getName(), e);
        }

    }

}
复制代码

 最后通过注解注入就可以使用

@Resource(name = "customExecutor")
private Executor executor;

 

posted @   二次元的程序猿  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示