前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Completablefuture

Completablefuture

作者头像
才疏学浅的木子
发布2024-04-11 08:29:26
610
发布2024-04-11 08:29:26
举报
文章被收录于专栏:CSDN文章CSDN文章

组成与作用

实现了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的是开启另一个线程来执行

常见使用

代码语言:javascript
复制
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();
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-04-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 组成与作用
    • Future
      • CompletionStage
      • 核心API
        • 创建类
          • 状态取值类
            • 控制完成行为
              • 其他
              • 常见使用
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档