From b548f47e25b8079577f373974f43a0c61ef0097c Mon Sep 17 00:00:00 2001 From: xiangwb Date: Fri, 9 Feb 2018 17:24:45 +0800 Subject: [PATCH] merge --- .../main/java/com/xwbing/demo/LambdaDemo.java | 4 ++-- .../src/main/java/com/xwbing/demo/demo.java | 17 ++++++++++++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java b/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java index 9168245..1e33407 100644 --- a/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java +++ b/boot-service/src/main/java/com/xwbing/demo/LambdaDemo.java @@ -83,11 +83,11 @@ public class LambdaDemo { reduce = optional.get(); } //异步回调 - List sysUsers = CompletableFuture.supplyAsync(LambdaDemo::getList).join(); + List sysUsers = CompletableFuture.supplyAsync(LambdaDemo::getList).join();//线程等待,效果等同于get(),会拋出CompletionException } /** - * 遍历集合,集合里数据还要进行复杂操作,导致速度很慢,可以用异步 + * 遍历集合,集合里数据还要进行复杂操作,导致速度很慢,可以用异步(无法保证顺序) */ public List supplyAsync() { List list = getList(); diff --git a/boot-service/src/main/java/com/xwbing/demo/demo.java b/boot-service/src/main/java/com/xwbing/demo/demo.java index fdfee2e..8e0f4a8 100644 --- a/boot-service/src/main/java/com/xwbing/demo/demo.java +++ b/boot-service/src/main/java/com/xwbing/demo/demo.java @@ -1,5 +1,8 @@ package com.xwbing.demo; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; /** @@ -10,6 +13,18 @@ import java.util.concurrent.ExecutionException; */ public class demo { public static void main(String[] args) throws ExecutionException, InterruptedException { - + List list = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + list.add(i); + } + List finalList = new ArrayList<>(); + int size = list.size(); + CompletableFuture[] futures = new CompletableFuture[size]; + for (int i = 0; i < size; i++) { + Integer integer = list.get(i); + futures[i] = CompletableFuture.supplyAsync(() -> finalList.add(integer)); + } + CompletableFuture.allOf(futures).join(); + System.out.println(finalList); } }