已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) {
}
});
}
自己的理解,有问题网友可以提出了修改。
本文详细介绍了如何使用XML配置文件以bean的方式配置Java线程池,包括核心线程数、最大线程数、任务队列容量和线程空闲时间等关键参数的设置。同时,展示了如何通过Spring框架的@Autowired注解注入线程池,并提供了一个具体的执行任务的示例。
1025

被折叠的 条评论
为什么被折叠?



