1,线程池配置类
package com.yfh.sportcompetitioncoursesite.map.config;
import cn.hutool.core.lang.Singleton;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* 线程池配置
* @author zdj
* @version 1.0
* @date 2022/12/19
*/
public class TaskPoolConfig {
private static volatile ThreadPoolTaskExecutor instance;
private TaskPoolConfig() {}
/**
* 采用双重校验锁进行获取线程池对象获取
* 全局只能有一个实例,不能进行new获取线程池对象
*/
public static ThreadPoolTaskExecutor getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.initialize();
int corePoolSize = Runtime.getRuntime().availableProcessors();
taskExecutor.setCorePoolSize(corePoolSize);
taskExecutor.setMaxPoolSize(corePoolSize * 2 + 1);
taskExecutor.setQueueCapacity(500);
taskExecutor.setKeepAliveSeconds(60);
taskExecutor.setThreadNamePrefix("custom-Async-");
taskExecutor.setWaitForTasksToCompleteOnShutdown(false);
taskExecutor.setAwaitTerminationSeconds(60);
/**
* 总共有四种拒绝策略,实际线程数量超过线程池设定的数量,将会启用拒绝策略
* 1. AbortPolicy(默认拒绝策略): 实际线程数量大于维护队列中设定的数量,将会触发拒绝任务的处理程序,它将抛出RejectedExecutionException
* 2. DiscardPolicy: 实际线程数量大于维护队列中设定的数量,将会被静默丢弃
* 3. DiscardOldestPolicy: 实际线程数量大于维护队列中设定的数量,将会把队列中最老的线程静默丢弃,把新的放进来
* 4. CallerRunsPolicy: 实际线程数量大于维护队列中设定的数量,多出来的线程由调用线程(主线程)处理
*/
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
instance = taskExecutor;
}
}
}
return instance;
}
}
2,使用
// 取出1000万条数据
List<SiteMessage> siteMessageList = siteMessageMapper.selectNeedPushSiteList();
if(!CollectionUtils.isEmpty(siteMessageList)){
// 获取线程池对象
ThreadPoolTaskExecutor instance = TaskPoolConfig.getInstance();
// 循环1000万条数据
siteMessageList.forEach(message -> {
instance.execute(() -> {
//循环每条数据,往线程池扔任务 并且 处理自己的业务
});
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/137444.html