bean 的方式使用线程池

已bean的方式配置

<bean id="cxxThreadPoolExecutor" class="cxx.executor.cxxThreadPoolExecutor">
    <!--corePoolSize:核心线程数-->
    <property name="corePoolSize" value="${threadPoolExecutor.corePoolSize}"/>
    <!--
       最大线程数
       当线程数>=corePoolSize,且任务队列已满时。线程池会创建新线程来处理任务
       当线程数=maxPoolSize,且任务队列已满时,线程池会拒绝处理任务而抛出异常
     -->
    <property name="maxPoolSize" value="${threadPoolExecutor.maxPoolSize}"/>
    <!--任务队列容量(阻塞队列)当核心线程数达到最大时,新任务会放在队列中排队等待执行 -->
    <property name="queueCapacity" value="${threadPoolExecutor.queueCapacity}"/>
    <!--线程空闲时间 -->
    <property name="keepAliveSeconds" value="5"/>
    <!--执行任务-->
    <property name="rejectedExecutionHandler">
        <bean class="java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy"/>
    </property>
</bean>

实现方式

@SuppressWarnings("serial")
public class CxxThreadPoolExecutor extends ThreadPoolExecutorFactoryBean {

    private boolean true;
    private int 40;
    private int 80;

    @Override
    protected ExecutorService initializeExecutor(ThreadFactory threadFactory,
                                                 RejectedExecutionHandler rejectedExecutionHandler) {

        if (autoStartKafka) {
            this.setCorePoolSize(kafkaCorePoolSize);
            this.setMaxPoolSize(kafkaMaxPoolSize);
        }

        return super.initializeExecutor(threadFactory, rejectedExecutionHandler);
    }
}
@Autowired
@Qualifier("cxxThreadPoolExecutor")
private ExecutorService cxxThreadPoolExecutor;
public void insertCosMessage(){
    //创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
   cxxThreadPoolExecutor.execute(() -> {
            try {
             pufe();
            } catch (Exception e) {
               
            }
    });
}

自己的理解,有问题网友可以提出了修改。

经验分享 程序员 微信小程序 职场和发展