IT袋

当前位置:主页 > 经验教程 > 建站编程 >

获取双异步返回值时

获取双异步返回值时 如何保证主线程不阻塞?(3)

时间:2024-01-25 18:00:14 来源:IT袋 作者:马勇
导读:获取双异步返回值时,2、thenAccept thenAccept()接受参数,没有返回值。 supplyAsync + thenAccept 异步线程顺序执行 supplyAsync的异步返回值,可以作为thenAccept的参数使用 不会阻塞主线程

获取双异步返回值时

获取双异步返回值时

2、thenAccept

thenAccept()接受参数,没有返回值。

supplyAsync + thenAccept

  1. 异步线程顺序执行
  2. supplyAsync的异步返回值,可以作为thenAccept的参数使用
  3. 不会阻塞主线程
CompletableFuture.supplyAsync(new Supplier<Integer>() {
    @Override
    public Integer get() {
        return readExcelDbJdk8Service.readXlsCacheAsyncMybatis();
    }
}).thenAccept(x -> logger.info(".thenAccept()方法测试:" + x));

获取双异步返回值时

但是,此时无法通过completableFuture.get()获取supplyAsync的返回值了。

3、thenApply

thenApply在thenAccept的基础上,可以再次通过completableFuture.get()获取返回值。

supplyAsync + thenApply,典型的链式编程。

  1. 异步线程内方法顺序执行
  2. supplyAsync 的返回值,作为第 1 个thenApply的参数,进行业务处理
  3. 第 1 个thenApply的返回值,作为第 2 个thenApply的参数,进行业务处理
  4. 最后,通过future.get()方法获取最终的返回值
CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(new Supplier<Integer>() {
 @Override
    public Integer get() {
        return readExcelDbJdk8Service.readXlsCacheAsyncMybatis();
    }
}).thenApply((result) -> {
    return thenApplyTest2(result);// supplyAsync返回值 * 2
}).thenApply((result) -> {
    return thenApplyTest5(result);// thenApply返回值 * 5
});
logger.info("readXlsCacheAsyncMybatis插入数据 * 2 * 5 = " + completableFuture.get());

获取双异步返回值时

七、CompletableFuture合并任务

  1. thenCombine,多个异步任务并行处理,有返回值,最后合并结果返回新的CompletableFuture对象;
  2. thenAcceptBoth,多个异步任务并行处理,无返回值;
  3. acceptEither,多个异步任务并行处理,无返回值;
  4. applyToEither,,多个异步任务并行处理,有返回值;

CompletableFuture合并任务的代码实例,这里就不多赘述了,一些语法糖而已,大家切记陷入低水平勤奋的怪圈。

八、CompletableFuture VS Future总结

本文中以下几个方面对比了CompletableFuture和Future的差异:

  1. ForkJoinPool和ThreadPoolExecutor的实现原理,探索了CompletableFuture和Future的差异;
  2. 通过代码实例的形式简单介绍了CompletableFuture中花俏的语法糖;
  3. 通过CompletableFuture优化了 “通过Future获取异步返回值”;
  4. 通过CompletableFuture.allOf解决阻塞主线程问题。

Future提供了异步执行的能力,但Future.get()会通过轮询的方式获取异步返回值,get()方法还会阻塞主线程。

轮询的方式非常消耗CPU资源,阻塞的方式显然与我们的异步初衷背道而驰。

JDK8提供的CompletableFuture实现了Future接口,添加了很多Future不具备的功能,比如链式编程、异常处理回调函数、获取异步结果不阻塞不轮询、合并异步任务等。

获取异步线程结果后,我们可以通过添加事务的方式,实现Excel入库操作的数据一致性。

以上是IT袋网网关于获取双异步返回值时 及其 如何保证主线程不阻塞的全部内容,您了解了吗?

相关阅读