求解: CompletableFuture 中 thenApplyAsync 和 thenApply 区别

@ther 2019-10-18 11:28:10
我看的网上说thenApplyAsync 是执行在异步线程池中的 thenApply 是在同一个线程中执行的
我做个了测试
private static void testThenApply2() {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
log.info("====future=====");
return 2;
});
future.thenApply(res -> {
log.info("====future=====");
return res + 1;
}).thenApply(res -> {
log.info("====future=====");
return res + 1;
}).thenAccept(res -> System.out.println(res));

CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
log.info("====future2=====");
return 2;
});
future2.thenApplyAsync(res -> {
log.info("====future2=====");
return res + 1;
}).thenApplyAsync(res -> {
log.info("====future2=====");
return res + 1;
}).thenAccept(res -> System.out.println(res));
}


其中 log.info 是
public void info(String mes) {
String name = Thread.currentThread().getName();
System.out.println("[ " + name + " ]: " + mes);
}

但是打印出来的结果是
[ ForkJoinPool.commonPool-worker-1 ]: ====future=====
[ ForkJoinPool.commonPool-worker-1 ]: ====future=====
[ ForkJoinPool.commonPool-worker-1 ]: ====future=====
4
[ ForkJoinPool.commonPool-worker-1 ]: ====future2=====
[ ForkJoinPool.commonPool-worker-1 ]: ====future2=====
[ ForkJoinPool.commonPool-worker-1 ]: ====future2=====
4
显示都是在同一个线程中的请问为什么会这样,求解决
...全文
1921 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧