了解 CompletableFuture::runAsync

Understanding CompletableFuture::runAsync

我刚刚阅读 the documentation 关于 CompletableFuture::runAsync 的内容,对其中的解释感到非常困惑。这是那里写的:

Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor after it runs the given action.

据我了解,CompletableFuture 看起来像 Future,它可以 "register" 某种回调并在给定操作完成后隐式调用它们。

考虑到这一点,让我们考虑以下代码:

ExecutorService threadsPool;
Runnable r;
//...
CompletableFuture.runAsync(r, threadsPool);

在这段代码中,我们在给定的 ThreadPool 中注册要异步执行的 Runnable

但是CompletableFuture是由一个task异步完成是什么意思呢?任务如何使 CompletableFuture 完成...?这对我来说意义不大。

CompletableFuture 中有以下代码被 runAsync 调用。

static CompletableFuture<Void> asyncRunStage(Executor e, Runnable f) {
    if (f == null) throw new NullPointerException();
    CompletableFuture<Void> d = new CompletableFuture<Void>();
    e.execute(new AsyncRun(d, f));
    return d;
}

AsyncRun 是异步执行的任务,它将在 运行 之后 Runnable f 异步完成 CompletableFuture d。我不会理会这里的代码,因为它提供的信息不多,它只是通过调用它的 postComplete() 方法(包私有的)来完成 d