Wondercease

浙ICP备2022017321号

CompletableFuture

  • Runnable就是没有返回结果的行为。
  • Callable是有返回结果的行为。
  • Future 异步封装Callable和Runnable,委托给线程池执行后,需要取回执行的结果
  • CompletableFuture 封装了Future,使其拥有了回调的功能,在某个行为完成之后,可以继续进行下一个动作。

CompletableFuture future = CompletableFuture.supplyAsync(() -> {

System.out.println(“电饭煲开始做饭”);

try{

TimeUnit.SECONDS.sleep(3);

}catch(InterruptedException e) {

e.printStackTrace();

}

return“白米饭”;

}).thenAccept(result -> {

System.out.println(“开始吃米饭”);

});

System.out.println(“我先去搞点牛奶和鸡蛋”);

future.join();

API方法分类

创建类

  • completeFuture 可以用于创建默认返回值
  • runAsync 异步执行,无返回值
  • supplyAsync 异步执行,有返回值
  • anyOf 任意一个执行完成,就可以进行下一步动作
  • allOf 全部完成所有任务,才可以进行下一步任务

状态取值类

  • join 合并结果,等待
  • get 合并等待结果,可以增加超时时间;get和join区别,join只会抛出unchecked异常,get会返回具体的异常
  • getNow 如果结果计算完成或者异常了,则返回结果或异常;否则,返回valueIfAbsent的值
  • isCancelled
  • isCompletedExceptionally
  • isDone

控制类 用于主动控制CompletableFuture的完成行为

  • complete
  • completeExceptionally
  • cancel

接续类

  • thenApply, thenApplyAsync
  • thenAccept, thenAcceptAsync
  • thenRun, thenRunAsync
  • thenCombine, thenCombineAsync
  • thenAcceptBoth, thenAcceptBothAsync
  • runAfterBoth, runAfterBothAsync
  • applyToEither, applyToEitherAsync
  • acceptEither, acceptEitherAsync
  • runAfterEither, runAfterEitherAsync
  • thenCompose, thenComposeAsync
  • whenComplete, whenCompleteAsync
  • handle, handleAsync
  • exceptionally

  1. Async结尾的方法,都是异步方法,对应的没有Async则是同步方法,一般都是一个异步方法对应一个同步方法。
  2. 以Async后缀结尾的方法,都有两个重载的方法,一个是使用内容的forkjoin线程池,一种是使用自定义线程池
  3. run开头的方法,其入口参数一定是无参的,并且没有返回值,类似于执行Runnable方法。
  4. supply开头的方法,入口也是没有参数的,但是有返回值
  5. Accept开头或者结尾的方法,入口参数是有参数,但是没有返回值
  6. Apply开头或者结尾的方法,入口有参数,有返回值
  7. 带有either后缀的方法,表示谁先完成就消费谁

CompletableFuture c1 = CompletableFuture

.runAsync(()->{System.out.println(“打开开关,开始制作,就不用管了”)});

CompletableFuture<String> c2 = CompletableFuture

.supplyAsync(()->{System.out.println(“清洗米饭”);return “干净的米饭”;});

// 只要有一个完成,则完成,有一个抛出异常,则携带异常

CompletableFuture.anyOf(c1,c2);

// 必须等待所有的future全部完成才可以

CompletableFuture.allOf(c1,c2);

取值与状态

arduino常用的是下面的这几种

// 不抛出异常,阻塞的等待

future.join()

// 有异常则抛出异常,阻塞的等待,无限等待

future.get()

// 有异常则抛出异常,最长等待1个小时,一个小时之后,如果还没有数据,则异常。

future.get(1,TimeUnit.Hours)

发表评论

您的电子邮箱地址不会被公开。