CompletableFuture使用

发布时间 2023-04-20 16:36:32作者: or追梦者

介绍

 

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

链式调用异常处理,不一定非要加在链尾

 

 

结合线程池使用

传进去就可以了