如何在不阻塞的情况下启动 CompletableFuture 并在完成后执行某些操作?

How do I start a CompletableFuture without blocking and do something when it's done?

CompletableFuture API 相当吓人,很多接受,然后等等;很难说为什么存在不同的选择。

CompletableFuture<?> future = CompletableFuture.supplyAsync(() ->..., executor)

future.startNonBlocking...( (...) -> { callback behavior done when complete }

我基本上是在尝试模仿 new Thread(() -> dostuff).start() 但具有更好的线程池、错误处理等。注意:我实际上并不需要这里的 Runnable 接口,我正在生成一段现有代码。

启动我的异步任务并在完成时执行行为的正确方法是什么?或处理抛出的异常?

这是一个简单的异步回调:

CompletableFuture.supplyAsync(() -> [result]).thenAccept(result -> [action]);

或者如果您需要错误处理:

CompletableFuture.supplyAsync(() -> [result]).whenComplete((result, exception) -> {
    if (exception != null) {
        // handle exception
    } else {
        // handle result
    }
});
new Thread(() -> dostuff).start()

意味着 dostuff 实现了 Runnable,所以你可以使用

static CompletableFuture<Void> runAsync(Runnable runnable)    
static CompletableFuture<Void> runAsync(Runnable runnable, Executor executor)

还有。