java - 在 CompletableFuture 中使用 thenXXXX 与 thenXXXXAsync 方法的性能影响
问题描述
我对使用 JDK 8 的 CompletableFuture 类的 thenXXXX 和 thenXXXXAsync 方法有疑问。根据我的理解,thenApply将使用与未来早期执行相同的线程,然后thenApplyAsync使用池中的任何线程。
代码_1:
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> tcf.task("FIRST"), executors)
.thenApply(a -> {
logger.log(Level.INFO, "Thread Id - 1 " + Thread.currentThread().getName());
////Some operations
})
.thenApply(a -> {
logger.log(Level.INFO, "Thread Id - 2 " + Thread.currentThread().getName());
////Some operations
});
输出:
线程 ID - 1:pool-1-thread-1线程 ID - 2:pool-1-thread-1
代码_2:
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> tcf.task("FIRST"), executors)
.thenApplyAsync(a -> {
logger.log(Level.INFO, "Thread Id - 1 " + Thread.currentThread().getName());
////Some operations
}, executors)
.thenApplyAsync(a -> {
logger.log(Level.INFO, "Thread Id - 2 " + Thread.currentThread().getName());
////Some operations
}, executors);
输出:
线程 ID - 1:pool-1-thread-2线程 ID - 2:pool-1-thread-3
哪个是最好的使用方法?在 Code_2 中,任务从一个线程移动到另一个线程。它会影响任何性能吗?
谢谢
解决方案
推荐阅读
- r - 使用 scatter3D 再现 pca 图时出错
- react-native - NavigatorIOS 错误:未定义不是对象(评估 routerArg.component)
- c++ - 具有递归的可变参数函数
- javascript - 如何在不同的屏幕上获取本地存储数据?
- c++ - 在某些情况下,std::is_floating_point 为 float 返回 false
- excel - VBA在Excel中为Word文档执行宏
- reactjs - 传递子组件的状态
- oracle - 序列生成器 Oracle 无法使用 import.sql
- security - ABAP 系统的 SNC 名称
- kubernetes - Kubernetes Cluster - 自动调度你的集群