private void method() throws ExecutionException, InterruptedException { CompletableFuturef1 = CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } return "f1"; }); f1.whenCompleteAsync(new BiConsumer () { @Override public void accept(String s, Throwable throwable) { System.out.println(System.currentTimeMillis() + ":" + s); } }); CompletableFuture f2 = CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } return "f2"; }); f2.whenCompleteAsync(new BiConsumer () { @Override public void accept(String s, Throwable throwable) { System.out.println(System.currentTimeMillis() + ":" + s); } }); CompletableFuture all = CompletableFuture.allOf(f1, f2); //阻塞,直到所有任务结束。 System.out.println(System.currentTimeMillis() + ":阻塞"); all.join(); System.out.println(System.currentTimeMillis() + ":阻塞结束"); //一个需要耗时2秒,一个需要耗时3秒,只有当最长的耗时3秒的完成后,才会结束。 System.out.println("任务均已完成。"); }
输出:
06-12 20:16:37.400 31142-31142/zhangphil.test I/System.out: 1528805797400:阻塞06-12 20:16:39.406 31142-31171/zhangphil.test I/System.out: 1528805799406:f206-12 20:16:40.404 31142-31170/zhangphil.test I/System.out: 1528805800404:f106-12 20:16:40.404 31142-31142/zhangphil.test I/System.out: 1528805800404:阻塞结束 任务均已完成。