美图
两个任务组合(一)
任务一和任务二都处理完成之后,才能处理任务三
runAfterBoth
组合两个future,不需要获取future的结果,只需要两个future处理完成后,处理该任务,无返回结果
CompletableFuture<Void> runAfterBoth(CompletionStage<?> other, Runnable action)
CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action)
CompletableFuture<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor)
示例
CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> System.out.println("任务1"));
CompletableFuture<Void> future2 = CompletableFuture.runAsync(() -> System.out.println("任务2"));
future1.runAfterBoth(future2, () -> System.out.println("任务3"));
thenAcceptBoth
组合两个future,需要获取future的结果,只需要两个future处理完成后,处理该任务,无返回结果
CompletableFuture<Void> thenAcceptBoth(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action)
CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action)
CompletableFuture<Void> thenAcceptBothAsync(CompletionStage<? extends U> other, BiConsumer<? super T, ? super U> action, Executor executor)
示例
CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务1");
return 10;
});
CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(() -> {
System.out.println("任务2");
return 20;
});
future1.thenAcceptBoth(future2, (res1, res2) -> {
System.out.println(<