CompletableFuture 异步编程

CompletableFuture 异步编程

Java8 新增一个类 CompletableFuture,用来支持流式异步编程。

创建任务

CompletableFuture 提供一下API用来执行异步任务。

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier);

static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor);

static CompletableFuture<Void> runAsync(Supplier<U> supplier);

static CompletableFuture<Void> runAsync(Supplier<U> supplier, Executor executor);

这些API都是用来创建任务,并且异步计算任务。supplyAsync 方法是有返回值的。例如:

CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "hello");

CompletableFuture<Void> futureB = CompletableFuture.supplyAsync(() -> "hello");
thenAccept()
CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action);

CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action, Executor executor);

表示当前这个阶段计算正常完成(没有异常发送),计算完成后的结果会作为 thenAcceptAsync 方法的入参,然后执行 action。如果当前阶段计算发送异常,thenAcceptAsync 方法不会被执行。

// 打印 hello
CompletableFuture.supplyAsync(() -> "hello")
               .thenAcceptAsync(result -> System.out.println(result));

// 不会打印. 因为不会执行thenAcceptAsync
CompletableFuture.supplyAsync(() -> {
   
                    throw new NullPointerException();
               })
               .thenAcceptAsync(rs -> System.out.println("1234"));
thenApply()
<U> CompletableFuture<U> thenApply(Function<?
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值