获取所有CompletableFuture的返回结果

走着路睡觉
  • java
  • CompletableFuture
小于 1 分钟

public static void main(String[] args) {
        final CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {

            try {
                log.info("future1");
                //Thread.sleep(1000L);
                log.info("future1---end");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "future1";
        });
        final CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {

            try {
                log.info("future2");
                //Thread.sleep(2000L);
                log.info("future2---end");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "future2";
        });
        final CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {

            try {
                log.info("future3");
                Thread.sleep(3000L);
                log.info("future3---end");
                //throw new RuntimeException("123");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "future3";

        });

        final ArrayList<CompletableFuture<String>> completableFutures = Lists.newArrayList(future1, future2, future3);
        for (CompletableFuture<String> completableFuture : completableFutures) {
            try {
            //打印返回结果,也可以list.add(completableFuture.get())
                System.out.println(completableFuture.get()+"-----------------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

        }
        System.out.println("main end");
    }
上次编辑于:
贡献者: zhaojingbo
Loading...