当前位置:   article > 正文

[AIGC] CompletableFuture的重要方法有哪些?

[AIGC] CompletableFuture的重要方法有哪些?

CompletableFuture具有多种方法,使其成为异步编程的强大工具。在这里,我们将介绍一些最重要和常用的方法:

  1. CompletableFuture<T> supplyAsync(Supplier<T> supplier): 使用ForkJoinPool.commonPool()作为线程池来异步执行Suppiler参数的get方法,并返回CompletableFuture。

  2. CompletableFuture<T> supplyAsync(Supplier<T> supplier, Executor executor): 使用指定的thread pool来异步执行Supplier参数的get()方法,并返回CompletableFuture。

  3. CompletableFuture<Void> thenRun(Runnable action): 当CompletableFuture的计算结果完成,便会进行如下操作,该方法不关心计算的结果。

  4. CompletableFuture<Void> thenRunAsync(Runnable action): 当CompletableFuture的计算结果完成后异步进行如下操作,通过ForkJoinPool.commonPool()作为它的线程池执行后续的Runnable参数。

  5. CompletableFuture<Void> thenRunAsync(Runnable action, Executor executor): 当CompletionStage的计算结果完成后异步进行如下操作,使用指定的thread pool。

  6. CompletableFuture<T> thenApply(Function<? super T,? extends U> fn): 当CompletableFuture的计算结果完成后,该方法返回一个新的CompletableFuture,这个新的CompletableFuture会对结果进行函数的处理。

  7. CompletableFuture<T> thenCompose(Function<? super T,? extends CompletionStage<U>> fn): 同thenApply类似,不同在于其输入函数的返回是CompletionStage而非值,这样可以有效处理嵌套的异步操作。

  8. CompletableFuture<T> exceptionally(Function<Throwable, ? extends T> fn): 当原有的CompletableFuture产出异常时,调用function,输入异常,返回新的值。

这些方法只是CompletableFuture的一部分,它还有许多其他的方法,可以在CompletableFuture文档中查看。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/717825
推荐阅读
相关标签
  

闽ICP备14008679号