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

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM