使用CompletableFuture執行多個異步任務,將結果合併返回

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()方法會阻塞
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS");
		data.put("task01",task01.get());
		System.out.printf("task01執行完畢;當前時間:%s\n",formatter.format(LocalDateTime.now()));
		data.put("task02",task02.get());
		System.out.printf("task02執行完畢;當前時間:%s\n",formatter.format(LocalDateTime.now()));
		data.put("task03",task03.get());
		System.out.printf("task03執行完畢;當前時間:%s\n",formatter.format(LocalDateTime.now()));
		return data;
	}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章