线程池配置

线程池配置

/**
 * 线程池配置
 */
@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 @ 2023-03-08 11:24  二次元的程序猿  阅读(40)  评论(0编辑  收藏  举报