了解CompletableFuture :: runAsync

St.*_*rio 5 java multithreading java-8 completable-future

我刚刚阅读有关的文档CompletableFuture::runAsync并对此解释感到困惑。这是那里写的:

返回一个新代码CompletableFuture,该新代码由在给定执行程序中运行的任务运行给定操作后异步完成。

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

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

ExecutorService threadsPool;
Runnable r;
//...
CompletableFuture.runAsync(r, threadsPool);
Run Code Online (Sandbox Code Playgroud)

在此代码中,我们在中注册了Runnable要异步执行的ThreadPool

但是CompletableFuture,由任务异步完成意味着什么。任务如何使CompletableFuture完成...?这对我来说没有多大意义。

Kay*_*man 5

内部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;
}
Run Code Online (Sandbox Code Playgroud)

AsyncRun是异步执行的任务,它将在运行后异步Runnable f完成CompletableFuture d。我不会在这里打扰代码,因为它的信息量不是很大,它只是d通过调用其postComplete()方法(package-private方法)来完成。

  • @walv 问题和答案中的所有示例都使用带有“Executor”参数的版本,这意味着不会使用公共池。 (2认同)