1、@Bean方式创建线程池并注入容器:
public class ThreadExecutorUtil {
/**
* 公共线程池
*/
private static final Logger logger = LoggerFactory.getLogger(ThreadExecutorConfig.class);
@Bean
public ThreadPoolTaskExecutor commonThreadPoolTaskExecutor() {
ThreadPoolTaskExecutor pool = new org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor();
logger.info(“线程池创建===>结束”);
int processNum = Runtime.getRuntime().availableProcessors(); // 返回可用处理器的Java虚拟机的数量 删除线格式
int corePoolSize = (int) (processNum / (1 - 0.2));
int maxPoolSize = (int) (processNum / (1 - 0.5));
pool.setCorePoolSize(corePoolSize); // 核心池大小
pool.setMaxPoolSize(maxPoolSize); // 最大线程数
pool.setQueueCapacity(maxPoolSize * 1000); // 队列程度
pool.setThreadPriority(Thread.MAX_PRIORITY);
pool.setDaemon(false);
pool.setKeepAliveSeconds(300);// 线程空闲时间
return pool;
}
}
2、在service中注入线程池
@Service
public class ContrastServiceimpl implements ContrastService{
/**
* 日志
*/
private static final Logger LOG = LoggerFactory.getLogger(ContrastServiceimpl.class);
@Autowired
private MybatisRepository mybatisRepository;
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor; // 注入线程池
//数据相似率对比处理
@Override
public void run() throws Exception {
try {
// 注入线程池
ExecutorCompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(threadPoolTaskExecutor);
long list_start = System.currentTimeMillis();//更新开始时间
LOG.info("列表数据查询开始");
List<Map> list = mybatisRepository.selectByParams("firstHomeMapper.DataList", "");
LOG.info("列表数据查询结束");
long list_end = System.currentTimeMillis();//更新结束时间
LOG.info("源数据列表查询程序运行时间:"+(list_end-list_start)+"毫秒");
int rows=1000;
for(;;) {
if(rows<=list.size()) {
// 这里做的事情就是 根据rows大小确认要多少个线程 给每个线程分配任务
int fromIndex = rows-1000;
int toIndex = rows;
// 从Future对象上获取任务的返回值
Future future = completionService.submit(new Callable() {
@Override
public Object call() throws Exception {
long constarst_start = System.currentTimeMillis();//处理开始时间
List<Map> list1 = list.subList(fromIndex, toIndex);
//此处编写业务逻辑处理代码
long constarst_end = System.currentTimeMillis();//处理结束时间
String result = "当前线程为:【"+Thread.currentThread().getName()+"】,执行用时为"+(constarst_end-constarst_start)+"毫秒";
LOG.debug(result);
return result;
}
});
// 这里是让多线程开始执行
try {
completionService.take().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
rows=rows+1000;
}else {
break;
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}