Java高併發解決方案之非同步處理
阿新 • • 發佈:2018-12-10
(() -> {
// 請求1
CompletableFuture<List<Integer>> completionStage1 = CompletableFuture.supplyAsync(() -> {
// 模擬請求
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<Integer> numberList = new ArrayList<>();
numberList.add(1);
numberList.add(2);
numberList.add(3);
numberList.add(4);
numberList.add(5);
System.out.println("請求1處理完成");
return numberList;
});
// 請求2
CompletableFuture<List<Integer>> completionStage2 = CompletableFuture.supplyAsync(() -> {
// 模擬請求
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
List<Integer> numberList = new ArrayList<>();
numberList.add(6);
numberList.add(7);
numberList.add(8 );
numberList.add(9);
numberList.add(10);
System.out.println("請求2處理完成");
return numberList;
});
// 請求3依賴請求2的結果
completionStage2.thenApplyAsync((request2Result) -> {
request2Result.add(11);
request2Result.add(12);
request2Result.add(13);
request2Result.add(14);
request2Result.add(15);
System.out.println("請求3依賴請求2的結果");
return request2Result;
});
// 組合請求1和請求3的結果
CompletableFuture<List<Integer>> completionStage =
completionStage1.thenCombine(completionStage2, (request1Result, request2Result) -> {
request1Result.addAll(request2Result);
System.out.println("合併處理結果");
return request1Result;
});
completionStage.whenComplete((list, ex) -> {
try {
asyncContext.getResponse().getWriter().write(JSONObject.toJSONString(list));
asyncContext.complete();
} catch (IOException e) {
e.printStackTrace();
}
});
});