我有以下ThreadPoolTaskExecutor,它们是使用预期的核心/最大池大小配置创建的。
@Slf4j
@Configuration
public class ThreadPoolConfig {
@Value("${corePoolSize}")
private Integer corePoolSize;
@Value("${queueCapacity}")
private Integer queueCapacity;
@Value("${maxPoolSize}")
private Integer maxPoolSize;
@Bean(name="myThreadPoolTaskExecutor")
public ThreadPoolTaskExecutor myThreadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setBeanName("myThreadPoolTaskExecutor");
executor.setCorePoolSize(corePoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setMaxPoolSize(maxPoolSize);
executor.setThreadNamePrefix("my_thread_");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.initialize();
log.debug("threadPoolTaskExecutor CorePoolSize is : " + executor.getCorePoolSize());
log.debug("threadPoolTaskExecutor MaxPoolSize is : " + executor.getMaxPoolSize());
return executor;
}
}
当我的@scheduled方法运行时,最大池大小设置为默认值2147483647
,我不明白为什么它没有使用上面配置的ThreadPoolTaskExecutor
:
@EnableScheduling
public class SchedulingConfig {
}
@Component
public class Scheduler {
@Autowired
@Qualifier("myThreadPoolTaskExecutor")
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
@Scheduled(fixedRateString = "${fixedRate}")
public void invokeScheduledThread() {
while (threadPoolTaskExecutor.getActiveCount() <= threadPoolTaskExecutor.getMaxPoolSize()) {
log.debug("Active Thread Pool count is : " + threadPoolTaskExecutor.getActiveCount() + ", Max Thread Pool count is : " + threadPoolTaskExecutor.getMaxPoolSize() + " on the scheduled Thread : " + Thread.currentThread().getName());
//call a service to retrieve some items to process
threadPoolTaskExecutor.execute(Some Object that implements runnable);
}
}
}
输出:
活动线程池计数为:0,最大线程池计数为:2147483647
在计划的线程上:task-scheduler-1
我在[{1}} initialise()
方法中加入了一个断点
看起来这个方法被调用了3次,两次使用了一个ThreadName前缀&#34; my_thread _&#34;
对于一个名为&#34; org.springframework.scheduling.concurrent.ExecutorConfigurationSupport
&#34; ThreadName前缀为&#34; taskScheduler
&#34;。
有谁知道为什么我不能在Scheduler类中使用我自己的task-scheduler-
?
我想使用默认的@Scheduler每x秒在一个线程上运行,并使用我自己的ThreadPoolTaskExecutor创建X个Thread。
答案 0 :(得分:1)
使用ThreadPoolTaskScheduler而不是ThreadPoolTaskExecutor。 例如:
@Configuration
public class SpringSchedulerConfig {
private static final int THREAD_POOL_SIZE = 5;
@Bean
public ThreadPoolTaskScheduler getScheduler() {
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
//we want every Job in a separate Thread.
threadPoolTaskScheduler.setPoolSize(THREAD_POOL_SIZE);
return threadPoolTaskScheduler;
}
}