异步常用方法

java异步编程常用方法:
CompletableFuture.runAsync(()->{});
传入是Runnable类型的参数,没有返回值。可自定义线程池,同supplyAsync()方法类似。
supplyAsync()方法:表示创建带返回值的异步任务,两种方法,第一种只需传入一个Supplier实例;另一种可以指定自定义的线程池,然后将任务提交给该线程池执行,如果不指定,默认使用ForkJoinPool.commonPool()。

allOf()方法:多个任务完成,返回一个全新的已完成CompletableFuture,有一个任务执行异常,调用get()方法时会抛出异常,如果都是正常执行,则返回null。

anyOf()方法:多个任务中任意一个任务完成,返回一个全新的已完成CompletableFuture,如果最快完成的任务执行异常,调用get()方法时会抛出异常,如果都是正常执行,则返回最快完成的任务结果。

completedFuture()方法:给定值,返回一个新的已完成的CompletableFuture。

get和join
相同点:
join()和get()方法都是阻塞调用它们的线程(通常为主线程)来获取CompletableFuture异步之后的返回值。
CompletableFuture.get() 和 CompletableFuture.join() 这两个方法是获取异步守护线程的返回值的。
不同点:
get() 方法会抛出经检查的异常,可被捕获,自定义处理或者直接抛出。
而 join() 会抛出未经检查的异常

thenApply有返回值,用作上一次结果的处理
thenAccept 无返回值,将结果消费掉
thenCompose返回的结果是带CompletableFuture的
thenComposeAsync 表示异步执行
thenCombineAsync 两个动作的完成,表示将两个异步任务组合起来一起执行
比较常用的是completedFuture()开启一个异步CompletableFuture
源码对比:

    public <U> CompletableFuture<U> thenCompose(
        Function<? super T, ? extends CompletionStage<U>> fn) {
        return uniComposeStage(null, fn);
    }

    public <U> CompletableFuture<U> thenComposeAsync(
        Function<? super T, ? extends CompletionStage<U>> fn) {
        return uniComposeStage(asyncPool, fn);
    }
    public <U> CompletableFuture<U> thenApply(
        Function<? super T,? extends U> fn) {
        return uniApplyStage(null, fn);
    }

    public <U> CompletableFuture<U> thenApplyAsync(
        Function<? super T,? extends U> fn) {
        return uniApplyStage(asyncPool, fn);
    }
    public CompletableFuture<Void> thenAccept(Consumer<? super T> action) {
        return uniAcceptStage(null, action);
    }

    public CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action) {
        return uniAcceptStage(asyncPool, action);
    }

    public <U,V> CompletableFuture<V> thenCombine(
        CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn) {
        return biApplyStage(null, other, fn);
    }

    public <U,V> CompletableFuture<V> thenCombineAsync(
        CompletionStage<? extends U> other,
        BiFunction<? super T,? super U,? extends V> fn) {
        return biApplyStage(asyncPool, other, fn);
    }
    public static CompletableFuture<Result<UserInfoRecord>> from(UserInfoRequest userInfoRequest) {
        return CompletableFuture.completedFuture(Result.succeeded(new UserInfoRecord(userInfoRequest)));
    }

使用thenApply以及thenAccept,thenCompose,thenComposeAsync

 circulationLoanDynamicServices.getCirList(loanDynamicVo)
                            .thenApply(circulationLoanDynamicServices::changeLogType)
                            .thenApply(result -> circulationLoanDynamicServices.createResult(result))
                            .thenAccept(res->res.writeTo(routingContext.response()));

或者直接创建一个CompletableFuture对象

 final CompletableFuture<AsyncResult<HttpResponse<Buffer>>> futureResponse
      = new CompletableFuture<>();

    final HttpRequest<Buffer> request = withStandardHeaders(
      webClient.getAbs(url));

    Stream.of(queryParameters)
      .forEach(parameter -> parameter.consume(request::addQueryParam));

    request
      .timeout(timeout.toMillis())
      .send(futureResponse::complete);

    return futureResponse
      .thenApply(asyncResult -> mapAsyncResultToResult(url, asyncResult));

allof方法的便捷使用:
使用list添加所有的CompletableFuture,然后使用allof获取最终所有的结果

   List<CompletableFuture<Result<JsonObject>>> futures = new ArrayList();
   
    futures.add(sendEmail(jsonObject,EMAIL_URL,okapiModulesClient));
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]))
                                .thenApply(v -> futures.stream().map(CompletableFuture::join).collect(Collectors.toList()))
                                .thenAccept(results->{
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值