开启多线程

在service层直接在方法上注解开启
@Async("getyourPool")

准备配置
@Configuration
@EnableAsync
@Slf4j
public class yourConfig {
@Value("${thread.pool.keepAliveSeconds:300}")
private int keepAliveSeconds;
@Value("${thread.pool.maxPoolSize:12}")
private int ingestionMaxPoolSize;
@Value("${thread.pool.corePoolSize:4}")
private int ingestionCorePoolSize;
@Value("${thread.pool.queueCapacity:600}")
private int ingestQueueCapacity;

@Bean
public ThreadPoolTaskExecutor getyourPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(ingestionCorePoolSize);
executor.setQueueCapacity(ingestQueueCapacity);
executor.setMaxPoolSize(ingestionMaxPoolSize);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setThreadNamePrefix("yourThreadPool-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setRejectedExecutionHandler((Runnable r, ThreadPoolExecutor exe) -> {
log.warn("yourThreadPool-full!");
});
executor.initialize();
return executor;
}
}
setQueueCapacity
如果设置了600,如果你的任务很多 超过600个 
例如1000个下载任务,如果你设置了600,那么你的任务开启到600个,剩余的400个任务会默认直接丢失,不会返回,
要设置
executor.setRejectedExecutionHandler 设置为不丢弃就行,不然默认直接丢弃 

 


还有一个问题是调用
@Async("getyourPool")注解的方法的时,不能用同一个类里调用这个方法,必须是不同的类中调用,不然不起效
 
posted @ 2023-06-19 17:54  ivyJ  阅读(47)  评论(0)    收藏  举报