我想根据特定条件跳过可完成的功能链。我尝试了在多个完成阶段进行链接时提出的解决方案,但似乎没有用。这里的代码:
@RunWith(JUnit4.class)
public class ExceptionHandlingTests {
@Test
public void test1() {
CompletableFuture<Integer> result = new CompletableFuture<>();
CompletableFuture.runAsync(() -> {
System.out.println("Completing result1. Result: " + result.isDone());
result.complete(10);
}).thenCompose(x -> {
System.out.println("Completing result2. Result: " + result.isDone());
result.complete(10);
return CompletableFuture.completedFuture(5);
}).thenCompose(x -> {
System.out.println("Completing result3. Result: " + result.isDone());
result.complete(10);
return CompletableFuture.completedFuture(5);
}).applyToEither(result, Function.identity());
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Completing result1. Result: false
Completing result2. Result: true
Completing result3. Result: true
Run Code Online (Sandbox Code Playgroud)
即使“结果”可完成期货被标记为已完成,后续的可完成期货仍将执行。如何跳过Completablefuture 2和3?