CompletableFuture中whenComplete()和thenApply()/thenAccept()区别
1.whenComplete()不使用ForkJoinPool中的线程,而是使用当前的主线程
DEMO:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { //使用ForkJoinPool线程 System.out.println("F1 "+Thread.currentThread().getName()); return "F1"; } ); //主线程 System.out.println(Thread.currentThread().getName()); CompletableFuture<String> future2 = future.whenComplete((s, throwable) -> { System.out.println(s); System.out.println(throwable); //使用主线程 System.out.println("F2 "+Thread.currentThread().getName()); }); future2.join(); System.out.println(future2.get());
输出结果
main F1 ForkJoinPool.commonPool-worker-1 F1 null F2 main F1
2.thenApply()/thenAccept()使用ForkJoinPool中的线程
DEMO
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> { //使用ForkJoinPool线程 System.out.println("F1 " + Thread.currentThread().getName()); return "F1"; } ).thenApply(s -> { //使用ForkJoinPool线程 System.out.println("F2 " + Thread.currentThread().getName()); return "F2"; }); future2.join(); System.out.println(future2.get());
输出:
F1 ForkJoinPool.commonPool-worker-1 F2 ForkJoinPool.commonPool-worker-1 F2