Completablefuture

组成与作用

实现了Future 与 CompletionStage这两个接口

Future

  • boolean cancel(boolean mayInterruptIfRunning)
  • boolean isCancelled()
  • boolean isDone()
  • V get()
  • V get(long timeout, TimeUnit unit)

CompletionStage

  • CompletionStage thenApply(Function<? super T,? extends U> fn)
  • CompletionStage thenApplyAsync(Function<? super T,? extends U> fn)
  • CompletionStage thenAccept(Consumer<? super T> action)

实现Future接口是为了能够得到数据
实现CompletionStage接口是为了能够流式处理
所以CompletableFuture封装了Future使其能够方法回调避免get()阻塞线程或者while()循环对CPU不好
Future判断任务是否完成就是get()或者idDone()循环不是很好,而Completablefuture可以直接方法回调与链式编程很方便

核心API

创建类

  • runAsync 异步执行,无返回值
  • supplyAsync 异步执行,有返回值
  • anyOf 有一个完成就往下执行
  • allOf 全部完成才往下执行

状态取值类

  • join 合并结果,等待
  • get 合并等待结果,可以增加超时时间;
  • getNow 如果结果计算完成或者异常了,则返回结果或异常;否则,返回valueIfAbsent的值
  • isCancelled
  • isCompletedExceptionally
  • isDone

控制完成行为

  • complete
  • completeExceptionally
  • cancel

其他

  • thenApply, thenApplyAsync
  • thenAccept, thenAcceptAsync
  • thenRun, thenRunAsync
  • thenCombine, thenCombineAsync
  • thenAcceptBoth, thenAcceptBothAsync
  • runAfterBoth, runAfterBothAsync

xxxAsync的是开启另一个线程来执行

常见使用

CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> System.out.println("runAsync"), Executors.newFixedThreadPool(4));
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "supplyAsync", Executors.newFixedThreadPool(4));
CompletableFuture.anyOf(future1, future2);
CompletableFuture.allOf(future1, future2);
future2.thenApply(s -> s + " " + "apply").thenAccept(e -> System.out.println(e)).join();
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

「已注销」

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值