Scala 期货 - 哪个线程执行 onComplete?

Scala futures - which thread executes onComplete?

在 Jason Goodwin 的 Learning Akka 中,我阅读了:

val future = getUsernameFromDatabaseAsync(userId)
future.onComplete(username =>
  //executed somewhere else
  println(username)
)

It's important to highlight again—the print statement will not run on the thread that registers the event. It will run somewhere else, on another thread via the ExecutionContext. Futures are always created with ExecutionContext, so you can choose where to run them.

出于好奇我想自己检查一下,所以我准备了一个片段:

val myFuture = Future {
  println("in future: " + Thread.currentThread().getName())
  Thread.sleep(1000)
}

myFuture.onComplete {
  case _ ⇒ println("in onComplete: " + Thread.currentThread().getName())
}

println("main: " + Thread.currentThread().getName())

Await.result(myFuture, 10 seconds)

我每次 运行 代码片段时都会得到以下输出。

main: main
in future: ForkJoinPool-1-worker-13
in onComplete: ForkJoinPool-1-worker-13

Future和onComplete在同一个线程执行,但是书上说,onComplete可能会在不同的线程执行回调。 怎么解释?

因为注册事件的线程是主线程,而不是运行未来的线程。在这种情况下,它没有在线程 main 上 运行 而是在线程 ForkJoinPool-1-worker-13

onComplete 和 future 可以 运行 在同一个线程上,因为 onComplete 仅在 future 结束后才开始。文档只是说明他们将 运行 在与主线程不同的线程上。