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));
        }


  • 相关阅读:
    算法中时间复杂度概括——o(1)、o(n)、o(logn)、o(nlogn)
    Docker笔记
    struts框架
    引包问题
    官网下载
    WebService
    答辩问题整理
    小程序转发功能的实现
    小程序自定义组件及传值
    vue 点击下拉框
  • 原文地址:https://www.cnblogs.com/dongma/p/14337887.html
Copyright © 2011-2022 走看看