CompletableFuturewhenComplete()和thenApply()/thenAccept()区别

书史足自悦,安用勤与劬。这篇文章主要讲述CompletableFuturewhenComplete()和thenApply()/thenAccept()区别相关的知识,希望能为你提供帮助。

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 F1ForkJoinPool.commonPool-worker-1 F1 null F2main F1

【CompletableFuturewhenComplete()和thenApply()/thenAccept()区别】 
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());

输出:
F1ForkJoinPool.commonPool-worker-1 F2ForkJoinPool.commonPool-worker-1 F2

 

    推荐阅读