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

public Map test() throws InterruptedException, ExecutionException {
	// 不存在并发插入情况,不需要使用ConcurrentHashMap
//		Map data = new ConcurrentHashMap<>(3);
	Map data = new HashMap<>(3);
	//第一个任务。返回参数类型可自定义
	CompletableFuture task01 = CompletableFuture.supplyAsync(() -> {
		try {
			TimeUnit.SECONDS.sleep(3);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "task01";
	});
	//第二个任务。返回参数类型可自定义
	CompletableFuture task02 = CompletableFuture.supplyAsync(() -> {
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "task02";
	});
	// 第三个任务。返回参数类型可自定义
	CompletableFuture 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;
}

你可能感兴趣的:(java,java,多线程)