CompletableFuture执行多个异步任务,将结果合并返回

该代码示例展示了如何在Java中使用CompletableFuture类来异步执行三个任务。每个任务通过supplyAsync启动并在不同的线程中运行,然后通过get()方法获取结果。尽管最初没有选择线程安全的ConcurrentHashMap,但考虑到不存在并发插入,使用了HashMap。最后,将任务的结果存储在一个Map中并返回。
public Map<String, String> test() throws InterruptedException, ExecutionException {
	// 不存在并发插入情况,不需要使用ConcurrentHashMap
//		Map<String, String> data = new ConcurrentHashMap<>(3);
	Map<String, String> data = new HashMap<>(3);
	//第一个任务。返回参数类型可自定义
	CompletableFuture<String> task01 = CompletableFuture.supplyAsync(() -> {
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "task01";
	});
	//第二个任务。返回参数类型可自定义
	CompletableFuture<String> task02 = CompletableFuture.supplyAsync(() -> {
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "task02";
	});
	// 第三个任务。返回参数类型可自定义
	CompletableFuture<String> task03 = CompletableFuture.supplyAsync(() -> {
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "task03";
	});
	// get()方法会阻塞,最终得到处理时间,取决于多线程的最大响应时间的接口
	String task01Result = task01.get() ;
	String task02Result = task02.get() ;
	String task03Result = task03.get() ;
	data.put("task01", task01Result );
	data.put("task02", task02Result );
	data.put("task03", task03Result );
	return data;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值