您的位置:首页 > 房产 > 建筑 > 网页设计模板html代码百度云_广告视频拍摄制作_个人网页设计_产品关键词怎么找

网页设计模板html代码百度云_广告视频拍摄制作_个人网页设计_产品关键词怎么找

2025/10/27 17:29:54 来源:https://blog.csdn.net/weixin_52173250/article/details/147285621  浏览:    关键词:网页设计模板html代码百度云_广告视频拍摄制作_个人网页设计_产品关键词怎么找
网页设计模板html代码百度云_广告视频拍摄制作_个人网页设计_产品关键词怎么找

一、CompletableFuture 概述

  • CompletableFuture 在 Java 里面被用于异步编程,异步通常意味着非阻塞,可以使得任务单独运行在与主线程分离的其他线程中,并且通过回调可以在主线程中得到异步任务的执行状态,是否完成,和是否异常等信息

  • CompletableFuture 实现了 Future, CompletionStage 接口,实现了 Future 接口就可以兼容现在有线程池框架,而 CompletionStage 接口是异步编程的接口抽象,里面定义多种异步方法,通过这两者集合,从而打造出了强大的 CompletableFuture 类


二、CompletableFuture 使用

1、无返回值的异步任务
(1)相关方法
  • runAsync 方法:异步调用没有返回值
public static CompletableFuture<Void> runAsync(Runnable runnable) {return asyncRunStage(asyncPool, runnable);
}
  • get 方法:阻塞直到任务结束后获取返回值
public T get() throws InterruptedException, ExecutionException {Object r;return reportGet((r = result) == null ? waitingGet(true) : r);
}
(2)具体实现
CompletableFuture<Void> completableFuture1 = CompletableFuture.runAsync(() -> {System.out.println(Thread.currentThread().getName() + " 1");
});
completableFuture1.get();
  • 结果
ForkJoinPool.commonPool-worker-9 1
2、有返回值的异步任务
(1)相关方法
  • supplyAsync 方法:异步调用有返回值
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {return asyncSupplyStage(asyncPool, supplier);
}
  • get 方法:阻塞直到任务结束后获取返回值
public T get() throws InterruptedException, ExecutionException {Object r;return reportGet((r = result) == null ? waitingGet(true) : r);
}
  • whenComplete 方法:异步调用完成后进行执行相关操作
public CompletableFuture<T> whenComplete(BiConsumer<? super T, ? super Throwable> action) {return uniWhenCompleteStage(null, action);
}
(2)具体使用
CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
System.out.println(Thread.currentThread().getName() + " 2");return 1024;
});
completableFuture2.whenComplete((t, u) -> {// 参数 t 为返回值System.out.println(t);// 参数 u 为异常System.out.println(u);
});
  • 结果
ForkJoinPool.commonPool-worker-9 2
1024
null

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com