Java 8 CompletableFuture - 如何运行 同一输入上的多个函数
Java 8 CompletableFuture - how to run multiple functions on same input
我有以下使用 CompleteableFuture
的工作代码:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync( () -> f1() ).
thenApplyAsync( f1Output -> f2( f1Output ) ).
thenApplyAsync( f2Output -> f3( f2Output ) );
是否有可能 运行 另一个接受 f1Output
作为 input?
的未来,例如:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync( () -> f1() ).
thenApplyAsync( f1Output -> f2( f1Output ) ).
someApiThatRuns( f1Output -> f4( f1Output ) ). // <--
thenApplyAsync( f2Output -> f3( f2Output ) );
如果这样可以简化事情,可以忽略 f4()
返回的结果。
如果您不介意按顺序 运行 宁 f2
和 f4
,最简单的方法就是在您的 lambda 中调用两者:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync(() -> f1() ).
thenApplyAsync(f1Output -> { f4(f1Output); return f2(f1Output); } ).
thenApplyAsync(f2Output -> f3(f2Output));
但是如果你想 运行 f2
和 f4
并行,你可以将中间的 future 存储在一个变量中:
CompletableFuture<SomeObject> f1Future = CompletableFuture.supplyAsync(() -> f1());
CompletableFuture<SomeObject> future = f1Future.
thenApplyAsync(f1Output -> f2(f1Output)).
thenApplyAsync(f2Output -> f3(f2Output));
f1Future.thenAcceptAsync(f1Output -> f4(f1Output));
我有以下使用 CompleteableFuture
的工作代码:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync( () -> f1() ).
thenApplyAsync( f1Output -> f2( f1Output ) ).
thenApplyAsync( f2Output -> f3( f2Output ) );
是否有可能 运行 另一个接受 f1Output
作为 input?
的未来,例如:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync( () -> f1() ).
thenApplyAsync( f1Output -> f2( f1Output ) ).
someApiThatRuns( f1Output -> f4( f1Output ) ). // <--
thenApplyAsync( f2Output -> f3( f2Output ) );
如果这样可以简化事情,可以忽略 f4()
返回的结果。
如果您不介意按顺序 运行 宁 f2
和 f4
,最简单的方法就是在您的 lambda 中调用两者:
CompletableFuture<SomeObject> future = CompletableFuture.
supplyAsync(() -> f1() ).
thenApplyAsync(f1Output -> { f4(f1Output); return f2(f1Output); } ).
thenApplyAsync(f2Output -> f3(f2Output));
但是如果你想 运行 f2
和 f4
并行,你可以将中间的 future 存储在一个变量中:
CompletableFuture<SomeObject> f1Future = CompletableFuture.supplyAsync(() -> f1());
CompletableFuture<SomeObject> future = f1Future.
thenApplyAsync(f1Output -> f2(f1Output)).
thenApplyAsync(f2Output -> f3(f2Output));
f1Future.thenAcceptAsync(f1Output -> f4(f1Output));