我刚刚读过文档 https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html#runAsync-java.lang.Runnable-java.util.concurrent.Executor- about CompletableFuture::runAsync
并且对这个解释感到非常困惑。这是那里写的内容:
返回一个新的CompletableFuture
这是由异步完成的
运行给定操作后在给定执行器中运行的任务。
据我了解,CompletableFuture
好像Future
这样它就可以“注册”某种回调,并在给定的操作完成后隐式调用它们。
考虑到这一点,让我们考虑以下代码:
ExecutorService threadsPool;
Runnable r;
//...
CompletableFuture.runAsync(r, threadsPool);
在此代码中我们注册了Runnable
在给定的时间内异步执行ThreadPool
.
但是这是什么意思CompletableFuture
由任务异步完成。任务如何才能使CompletableFuture
完成...?这对我来说没有多大意义。
Inside 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
异步地。我不会打扰这里的代码,因为它的信息量不大,它只是执行以下操作的完成d
通过调用其postComplete()
方法(包私有的方法)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)