zoukankan      html  css  js  c++  java
  • CompletableFuture.allOf that doens't return Void(CompletableFuture.allOf不能返回Void的解决方法)

    import java.util.List;
    import java.util.concurrent.CompletableFuture;
    import java.util.concurrent.TimeUnit;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Main {
    
        static CompletableFuture<List<?>> allOf(CompletableFuture<?>... cfs) {
            return CompletableFuture.allOf(cfs)
                    .thenApply(ignore -> Stream.of(cfs)
                            .map(cf -> cf.join())
                            .collect(Collectors.toList()));
        }
    
        public static void main(String[] args) {
    
            // we have 3 (or any number) of CompletableFutures
            CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {sleep(1); return "HELLO";});
            CompletableFuture<Integer> cf2 = CompletableFuture.supplyAsync(() -> {sleep(1); return 10;});
            CompletableFuture<Double> cf3 = CompletableFuture.supplyAsync(() -> {sleep(1); return 20d;});
    
            CompletableFuture<List<?>> allOf = allOf(cf1, cf2, cf3); //we call the method we just created above
    
            // we can get the -already there - result either using then
            // Get result using:
            allOf.thenAccept(l -> l.forEach(System.out::println));
    
            // or using CompletableFuture.join() (or CompletableFuture.get())
            // OR (non-typesafe)
            String s = (String) allOf.join().get(0);
            Integer i = (Integer) allOf.join().get(1);
            Double d = (Double) allOf.join().get(2);
            System.out.println(s + ", " + i + ", "+ d);
    
            sleep(2); // because default CompletableFuture Executor is a daemon-thread based executor
        }
    
        private static void sleep(int seconds) {
            try {
                TimeUnit.SECONDS.sleep(seconds);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    摘录地址:http://m-hewedy.blogspot.com/2017/02/completablefutureallof-that-doenst.html

  • 相关阅读:
    如何把一个一般的git库变成“裸库”?
    MacOSX下杀掉sudo进程
    nginx FastCGI错误Primary script unknown解决办法
    Lua继承userdata
    Unity图文混排
    C++轻量级跨平台文件系统API
    lua_next()
    重载方法匹配算法
    C++模板函数只能全特化不能偏特化
    xcode离线安装包下载
  • 原文地址:https://www.cnblogs.com/passedbylove/p/11184830.html
Copyright © 2011-2022 走看看