同じものではないです。 2番目の例では、thenApply
を使用しない場合は、convertToB
への呼び出しがメソッドdoSomethingAndReturnA
と同じスレッドで実行されていることが確認されています。
しかし、thenApply
メソッドが使用されたときの最初の例では、他のことが起こる可能性があります。
まず、doSomethingAndReturnA
を実行するCompletableFuture
が完了すると、thenApply
の呼び出しが呼び出し元スレッドで行われます。 CompletableFutures
が完了していない場合はthenApply
に渡されたFunction
がdoSomethingAndReturnA
と同じスレッドで呼び出されます。
混乱しますか?よくthis article might be helpful(リンクのために@SotiriosDelimanolisに感謝)。
thenApply
がどのように機能するかを示す簡単な例を示しました。
public class CompletableTest {
public static void main(String... args) throws ExecutionException, InterruptedException {
final CompletableFuture<Integer> future = CompletableFuture
.supplyAsync(() -> doSomethingAndReturnA())
.thenApply(a -> convertToB(a));
future.get();
}
private static int convertToB(final String a) {
System.out.println("convertToB: " + Thread.currentThread().getName());
return Integer.parseInt(a);
}
private static String doSomethingAndReturnA() {
System.out.println("doSomethingAndReturnA: " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "1";
}
}
、出力がある:
doSomethingAndReturnA: ForkJoinPool.commonPool-worker-1
convertToB: ForkJoinPool.commonPool-worker-1
最初の操作(すなわちCompletableFuture
がまだ完了していない)遅いときに、両方の呼び出しが同じスレッドで起こります。しかし、我々はdoSomethingAndReturnA
からの出力をThread.sleep
-callを削除した場合には、このようなこと(あり):convertToB
呼び出しはmain
スレッドであることを
doSomethingAndReturnA: ForkJoinPool.commonPool-worker-1
convertToB: main
注意。
この回答とこの投稿(http://www.deadcoderising.com/java8-writing-asynchronous-code-with) -completablefuture /)CompletableFutureを理解するために助けてください – Jesus
これはなぜ、なぜ「thenApply」を使うのか説明していませんか? – Yamcha
最初のケースでは、 '' 'ForkJoinPool.commonPool-worker-1'''は' 'doSomethingAndReturnA'''が返るまで待っていますか? – Siddhartha