zoukankan      html  css  js  c++  java
  • CompletableFuture 获取所有task的结果

    前置知识
    1,CompletableFuture 使用supplyAsync 可以直接执行,并得到返回结果
    2,CompletableFuture get方法,可以得到最终的结果
    代码
    private void foreachGet() throws ExecutionException, InterruptedException {
            Random random = new Random();
            long mainstart = System.currentTimeMillis();
            List<CompletableFuture<String>> futureList = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
                    System.out.println(Thread.currentThread()+",begin");
                    long start = System.currentTimeMillis();
                    int time = random.nextInt(3000);
                    try {
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    long end = System.currentTimeMillis();
                    System.out.println(Thread.currentThread()+",cost:"+(end - start));
                    System.out.println(Thread.currentThread()+",end");
                    return time+"";
                });
                futureList.add(future);
            }
    
            for (CompletableFuture<String> future : futureList) {
                future.get();
            }
            long mainend = System.currentTimeMillis();
            System.out.println(Thread.currentThread()+" is end:"+(mainend - mainstart));
        }


  • 相关阅读:
    Hadoop无法访问web50070端口
    Hadoop问题汇总
    Hadoop问题汇总
    Linux网络连接模式以及修改静态IP
    Linux网络连接模式以及修改静态IP
    Linux基本命令
    SQLite数据操作
    SQLite初试
    编码与解码
    属性列表
  • 原文地址:https://www.cnblogs.com/dongma/p/14337887.html
Copyright © 2011-2022 走看看