Java CompletableFuture:allOf等待所有异步线程任务结束

/**
 * 使用java8 CompletableFuture.runAsync实现 多线程处理,获取治理任务明细
 * 使用线程安全list synchronizedList
 * @param env
 * @param systemEnNameList
 * @param ldcList
 * @param instanceList
 * @param strategyMap
 * @param actStrategyMap
 * @param unActStrategyMap
 * @param activitedSystemList
 * @param unActivitedSystemList
 * @return
 */
private List<ResourceRuleTaskDetail> getTaskDetailsUseThreads(String env, List<String> systemEnNameList, List<String> ldcList, List<String> instanceList, Map<String, JSONArray> strategyMap, Map<String, JSONArray> actStrategyMap, Map<String, JSONArray> unActStrategyMap, List<String> activitedSystemList, List<String> unActivitedSystemList) {
	// 对于集合写操作:synchronizedList 相对于Vector 、CopyOnWriteArrayList性能更佳。 读操作建议CopyOnWriteArrayList
	List<ResourceRuleTaskDetail> resourceRuleTaskDetailList = Collections.synchronizedList(new ArrayList<ResourceRuleTaskDetail>());
	CompletableFuture<Void> cf1 = CompletableFuture.runAsync(()->{
		if (MapUtils.isNotEmpty(strategyMap)) {
			List<ResourceRuleTaskDetail> strategyTaskDetailList = resourceDealStrategyNewService.dealStrategyToGetGovernDataNew(systemEnNameList, ldcList, env, strategyMap, instanceList);
			resourceRuleTaskDetailList.addAll(strategyTaskDetailList);
		}
	});

	CompletableFuture<Void> cf2 = CompletableFuture.runAsync(()->{
		if (MapUtils.isNotEmpty(actStrategyMap) && CollectionUtils.isNotEmpty(activitedSystemList)) {
			List<ResourceRuleTaskDetail> actStrategyTaskDetailList = resourceDealStrategyNewService.dealStrategyToGetGovernDataNew(activitedSystemList, ldcList, env, actStrategyMap, instanceList);
			resourceRuleTaskDetailList.addAll(actStrategyTaskDetailList);
		}
	});
	CompletableFuture<Void> cf3 = CompletableFuture.runAsync(()->{
		if (MapUtils.isNotEmpty(unActStrategyMap) && CollectionUtils.isNotEmpty(unActivitedSystemList)) {
			List<ResourceRuleTaskDetail> unActStrategyTaskDetailList = resourceDealStrategyNewService.dealStrategyToGetGovernDataNew(unActivitedSystemList, ldcList, env, unActStrategyMap, instanceList);
			resourceRuleTaskDetailList.addAll(unActStrategyTaskDetailList);
		}
	});
	// join等待所有线程执行完成
	CompletableFuture.allOf(cf1, cf2, cf3).join();
	return resourceRuleTaskDetailList;
}
posted @ 2021-07-07 14:39  王岳阳  阅读(2869)  评论(0编辑  收藏  举报