java8 CompletableFuture.supplyAsync +线程池 实现多线程处理

public void dealGovernanceStrategyNew(List<StrategyStreamOperation> commonAll, StrategyDetail strategyDetail, List<String> instanceList) {
	if (Objects.isNull(strategyDetail.getType()) && Objects.isNull(strategyDetail.getRetainNum())) {
		// 500一组分批处理
		List<List<String>> lists = ListSplitUtil.splitList(instanceList, 500);
		// 对于集合写操作:synchronizedList 相对于Vector 、CopyOnWriteArrayList性能更佳。 读操作建议CopyOnWriteArrayList
		// 多线程批量处理数据(500一组) 这里使用java8 CompletableFuture.supplyAsync实现多线程处理
		List<StrategyStreamOperation> operationList = Collections.synchronizedList(new ArrayList<>());
		// 手动创建线程池
		ExecutorService executorService =  new ThreadPoolExecutor(lists.size(), lists.size(), 0, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>(1024), new ThreadPoolExecutor.AbortPolicy());
		lists.stream().forEach((List<String> item) ->{
			CompletableFuture<List<StrategyStreamOperation>> cf = CompletableFuture.supplyAsync(()->{
				// 持续天数的峰值判断的
				List<StrategyStreamOperation> futureList = getStrategyByCommon();
				return futureList;
			}, executorService);
			try {
				// 获取线程执行结果
				operationList.addAll(cf.get());
			} catch (InterruptedException e) {
				log.error("从线程中获取执行结果失败", e);
			} catch (ExecutionException e) {
				log.error("从线程中获取执行结果失败", e);
			}
		});
		// 关闭线程池,不再接收新任务
		executorService.shutdown();
		commonAll.addAll(operationList);
	}
}
每天一点点,惊喜不间断
原文地址:https://www.cnblogs.com/wszn-java/p/15039415.html