当前位置: 首页 > news >正文

【CompletableFuture】常用方法(三)

【CompletableFuture】方法使用

  • 1. 线程池的使用
  • 2. 异步任务的串行执行
    • 2.1 thenApply 方法
      • 2.1.1 thenApply(Function<? super T, ? extends U> fn)
      • 2.1.2 thenApplyAsync(Function<? super T, ? extends U> fn)
      • 2.1.3 thenApplyAsync(Function<? super T, ? extends U> fn, Executor executor)
      • 2.1.4
    • 2.2 thenRun 方法

1. 线程池的使用

默认情况下通过静态方法 runAsyncsupplyAsync 创建的 CompletableFuture 任务会使用公
共的 ForkJoinPool 线程池,其默认的线程数是 CPU 的核数。当然,其线程数可以通过以下 JVM
参数去设置:
option:-Djava.util.concurrent.ForkJoinPool.common.parallelism

问题是:如果所有 CompletableFuture 共享一个线程池,那么一旦有任务执行一些很慢的 IO
操作,就会导致线程池中所有线程都阻塞在 IO 操作上,从而造成线程饥饿,进而影响整个系统
的性能。所以,强烈建议大家根据不同的业务类型创建不同的线程池,以避免互相干扰。

所以,建议大家在生产环境使用时,根据不同的业务类型创建不同的线程池,以避免互相影
响。前面第一章为大家介绍了三种线程池:IO 密集型任务线程池、CPU 密集型任务线程池、混合
型任务线程池。大家可以根据不同的任务类型,确定线程池的类型和线程数。

作为演示,这里使用“混合型任务线程池”执行CompletableFuture任务,具体的代码如下:
在这里插入图片描述
在这里插入图片描述

2. 异步任务的串行执行

如果两个异步任务需要串行(当一个任务依赖另一个任务)执行,可以通过 CompletionStage
接口的 thenApply、thenAccept、thenRun 和 thenCompose 四个方法实现。

2.1 thenApply 方法

thenApply 方法有三个重载版本,三个版本的声明如下:

// 后一个任务与前一个任务在同一个线程中执行
public <U> CompletableFuture<U> thenApply(Function<? super T,? extends U> fn)// 后一个任务与前一个任务可以不在同一个线程中执行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn)// 后一个任务在指定的 executor 线程池中执行
public <U> CompletableFuture<U> thenApplyAsync(Function<? super T,? extends U> fn, Executor executor)

thenApply 三个重载版本有一个共同的参数 fn,该参数表示待串行执行的第二个异步任务,
其类型为 Function。fn 的类型声明涉及到两个范型参数,具体如下:

  • 范型参数 T:上一个任务所返回结果的类型。
  • 范型参数 U:当前任务的返回值类型。

作为示例,使用 thenApply 分两步计算(10+10)*2,代码如下:
在这里插入图片描述
在这里插入图片描述

Function<T, R>接口既能接收参数也支持返回值,所以 thenApply 可以将前一个任务的结果,
通过 FunctionR apply(T t) 方法传递给到第二个任务,并且能输出第二个任务的执行结果。

2.1.1 thenApply(Function<? super T, ? extends U> fn)

再举一个🌰

同步执行:后一个任务和前一个任务 在同一个线程中执行(如果前一个任务是异步的,使用的是那个线程)。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {System.out.println("任务1线程: " + Thread.currentThread().getName());return "hello";
}).thenApply(result -> {System.out.println("任务2线程: " + Thread.currentThread().getName());return result.toUpperCase();
});
future.join();

输出的结果:

任务1线程: ForkJoinPool.commonPool-worker-1
任务2线程: ForkJoinPool.commonPool-worker-1

✅ 任务2复用了任务1的线程。

2.1.2 thenApplyAsync(Function<? super T, ? extends U> fn)

异步执行(默认线程池):后一个任务在公共线程池中异步执行,不一定和前一个任务在同一个线程。

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {System.out.println("任务1线程: " + Thread.currentThread().getName());return "hello";
}).thenApplyAsync(result -> {System.out.println("任务2线程: " + Thread.currentThread().getName());return result.toUpperCase();
});
future.join();
任务1线程: ForkJoinPool.commonPool-worker-1
任务2线程: ForkJoinPool.commonPool-worker-3

✅ 任务2可能使用不同的线程(ForkJoinPool)执行。

2.1.3 thenApplyAsync(Function<? super T, ? extends U> fn, Executor executor)

异步执行(指定线程池):后一个任务在你提供的 Executor 线程池中执行,更灵活控制线程来源。

ExecutorService executor = Executors.newFixedThreadPool(2);CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {System.out.println("任务1线程: " + Thread.currentThread().getName());return "hello";
}).thenApplyAsync(result -> {System.out.println("任务2线程: " + Thread.currentThread().getName());return result.toUpperCase();
}, executor);future.join();
executor.shutdown();

输出可能:

任务1线程: ForkJoinPool.commonPool-worker-1
任务2线程: pool-1-thread-1

✅ 任务2明确使用了你自己创建的线程池中的线程。

2.1.4

方法名是否异步使用线程是否可指定线程池
thenApply同前任务线程
thenApplyAsync(fn)默认线程池(ForkJoinPool)
thenApplyAsync(fn, executor)指定线程池✅ 是

2.2 thenRun 方法

相关文章:

  • JetsonNano详细使用笔记(二)
  • CentOS 7 虚拟机网络配置异常 典型问题:启动了NetworkManager但是network无法启动
  • 家用旧电脑搭建小型服务器操作步骤教程:一步一步本地部署到公网访问
  • 升级OpenSSL和OpenSSH 修复漏洞
  • InputStream重复读取导致文件损坏问题解决方案
  • 【C分解多位整数输出1位数2各位空格最后无空格3倒序/读取指定字符否则退出】2022-6-29
  • Flask设计网页截屏远程电脑桌面及切换运行程序界面
  • Javaweb学习——day6(JDBC入门 CRUD)
  • 【Unity】MiniGame编辑器小游戏(三)马赛克【Mosaic】
  • EPOLL相关接口和原理
  • CppCon 2016 学习:BUILDING A MODERN C++ FORGE FOR COMPUTE AND GRAPHICS
  • 如何将数据从安卓设备传输到 iPhone | 综合指南
  • 【QT】QT项目修改QT设计师界面类类名和文件名的方法
  • 408第二季 - 组成原理 - 数据类型转换
  • 在linux上用nginx配置ssl应该怎么操作?下面是示例
  • Python实现企业微信Token自动获取到SQLite存储
  • 微服务拆分 SpringCloud
  • 渲染学进阶——机械动力的渲染(3)
  • 对微服务的了解
  • 准确识别检索头,提高大模型长上下文能力
  • 机关网站建设创新/seo优化排名
  • 网页设计与网站建设课程报告/seo关键字怎么优化
  • 网站开发简答题/晨阳seo
  • 产品推广介绍/优化网站排名的方法
  • 中小企业网站开发/专业网络推广公司排名
  • 做百度收录的网站/怎么理解搜索引擎优化