CompletableFuture使用
介绍
A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.
可以明确完成(设置其值和状态)并可以用作CompletionStage的Future,它支持在完成时触发的相关功能和操作
When two or more threads attempt to complete, completeExceptionally, or cancel a CompletableFuture, only one of them succeeds
当两个或多个线程尝试完成,completeExceptionally或取消CompletableFuture时,只有其中一个成功
主要实现异步回调,比futureTask语法更美观
有现成的轮子 : MQ
使用
代替futureTask,语法更简洁美观
join
返回completabletFutre的结果 ,有异常会抛出异常
/** * Returns the result value when complete, or throws an * (unchecked) exception if completed exceptionally. To better * conform with the use of common functional forms, if a * computation involved in the completion of this * CompletableFuture threw an exception, this method throws an * (unchecked) {@link CompletionException} with the underlying * exception as its cause. * * @return the result value * @throws CancellationException if the computation was cancelled * @throws CompletionException if this future completed * exceptionally or a completion computation threw an exception */ public T join() { Object r; return reportJoin((r = result) == null ? waitingGet(false) : r); }
回调使用
组合使用
小结
thenApply
前面的结果传给后面使用,在同一个线程中
thenApplyAsync
前面的结果传给后面使用,异步操作
applyToEither
public <U> CompletableFuture<U> applyToEither( CompletionStage<? extends T> other, Function<? super T, U> fn) { return orApplyStage(null, other, fn); }
谁先完成,返回谁的结果
Exceptioinally
链式调用异常处理,不一定非要加在链尾
结合线程池使用
传进去就可以了
作者: deity-night
出处: https://www.cnblogs.com/deity-night/
关于作者:码农
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(***@163.com)咨询.