组成与作用
实现了Future 与 CompletionStage这两个接口
Future
- boolean cancel(boolean mayInterruptIfRunning)
- boolean isCancelled()
- boolean isDone()
- V get()
- V get(long timeout, TimeUnit unit)
CompletionStage
- CompletionStage thenApply(Function<? super T,? extends U> fn)
- CompletionStage thenApplyAsync(Function<? super T,? extends U> fn)
- CompletionStage thenAccept(Consumer<? super T> action)
- …
实现Future接口是为了能够得到数据
实现CompletionStage接口是为了能够流式处理
所以CompletableFuture封装了Future使其能够方法回调避免get()阻塞线程或者while()循环对CPU不好
Future判断任务是否完成就是get()或者idDone()循环不是很好,而Completablefuture可以直接方法回调与链式编程很方便
核心API
创建类
- runAsync 异步执行,无返回值
- supplyAsync 异步执行,有返回值
- anyOf 有一个完成就往下执行
- allOf 全部完成才往下执行
状态取值类
- join 合并结果,等待
- get 合并等待结果,可以增加超时时间;
- getNow 如果结果计算完成或者异常了,则返回结果或异常;否则,返回valueIfAbsent的值
- isCancelled
- isCompletedExceptionally
- isDone
控制完成行为
- complete
- completeExceptionally
- cancel
其他
- thenApply, thenApplyAsync
- thenAccept, thenAcceptAsync
- thenRun, thenRunAsync
- thenCombine, thenCombineAsync
- thenAcceptBoth, thenAcceptBothAsync
- runAfterBoth, runAfterBothAsync
xxxAsync的是开启另一个线程来执行
常见使用
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> System.out.println("runAsync"), Executors.newFixedThreadPool(4));
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "supplyAsync", Executors.newFixedThreadPool(4));
CompletableFuture.anyOf(future1, future2);
CompletableFuture.allOf(future1, future2);
future2.thenApply(s -> s + " " + "apply").thenAccept(e -> System.out.println(e)).join();