我想执行CompletableFuture
一次又一次的CompletableFuture
完成,无论第一个是否异常完成(.thenCompose()
仅在执行正常完成时运行).
例如:
CompletableFuture.supplyAsync(() -> 1L) .whenComplete((v, e) -> CompletableFuture.runAsync(() -> { try { Thread.sleep(1000); System.out.println("HERE"); } catch(InterruptedException exc) { return; } })) .whenComplete((v, e) -> System.out.println("ALL DONE"));
这打印
ALL DONE HERE
我希望它是
HERE ALL DONE
优选地,不将第二个嵌套在第一个whenComplete()
内部.
请注意,我不关心返回的结果/异常.
诀窍是用来.handle((r, e) -> r)
抑制错误:
CompletableFuture.runAsync(() -> { throw new RuntimeException(); }) //Suppress error .handle((r, e) -> r) .thenCompose((r) -> CompletableFuture.runAsync(() -> System.out.println("HELLO")));