CompletableFuture 案例

private static ThreadFactory namedTreadFactory = new ThreadFactoryBuilder().setNameFormat("lottery-pool-%d").build();

private static ExecutorService doLotteryPool = new ThreadPoolExecutor(1, 5,
    60L, TimeUnit.SECONDS,
    new LinkedBlockingDeque<>(2),
    namedTreadFactory,
    new ThreadPoolExecutor.CallerRunsPolicy());

public static void main(String[] args) {


    Long start = System.currentTimeMillis();
    // 结果集
    List<String> list = new ArrayList<>();


    List<Integer> taskList = Arrays.asList(2, 1, 3,2, 1, 3,2, 1, 3,2, 1, 3,2, 1, 3,2, 1, 3,2, 1, 3);
    // 全流式处理转换成CompletableFuture[]+组装成一个无返回值CompletableFuture,join等待执行完毕。返回结果whenComplete获取
    List<CompletableFuture<String>> futures = taskList.stream()
        .map(integer ->

            CompletableFuture.supplyAsync(() ->
                    calc(integer),
                doLotteryPool)
                //当计算完成的时候请执行某个function
                .thenApply(h ->
                    thenApply(h)
                )
                //计算结果完成时的处理
                .whenComplete((s, e) -> {
                    System.out.println("任务" + s + "完成!result=" + s + ",异常 e=" + e + "," + new Date());
                    list.add(s);
                })
                .exceptionally(e -> {
                    //e.printStackTrace();
                    System.out.println("出现异常"+e);
                    //返回一个默认值
                    return "0";
                })
        ).collect(Collectors.toList());

    // 封装后无返回值,必须自己whenComplete()获取
    CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).join();
    System.out.println("list=" + list + ",耗时=" + (System.currentTimeMillis() - start));

    // 输出结果;

    //获取值
    System.out.println("----------等待结果返回-------------");
    String res = futures.stream()
        .map(f -> {
            try {
                return f.thenApply(String::valueOf).get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "";
        }).collect(Collectors.joining(" , ", "", ""));
    System.out.println("res = " + res);
}

private static String thenApply(Integer h) {
    System.out.println("当计算完成的时候请执行某个function");
    return Integer.toString(h);
}

public static Integer calc(Integer i) {
    try {
        if (i == 1) {
            Thread.sleep(3000);//任务1耗时3秒
        } else if (i == 5) {
            Thread.sleep(5000);//任务5耗时5秒
        } else {
            Thread.sleep(1000);//其它任务耗时1秒
        }
        System.out.println("task线程:" + Thread.currentThread().getName()
            + "任务i=" + i + ",完成!+" + new Date());
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    if(i==3){
        int num=1/0;
    }

    return i;
}