求解: 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
显示都是在同一个线程中的请问为什么会这样,求解决