在以下使用Scala异步的示例方法实现中:
def doSomething: Future[Int] = async {
val await1 = await(someFutureResult1()) // Line 1
val await2 = await(someFutureResult2()) // Line 2
val syncCall = someFunc3() // Line 3
await1 + await2 + syncCall // Line 4
}
如何进行排序? doSomething的调用者立即返回,因为doSomething()将在异步块中运行。我明白了。但是当其他一些线程接受执行并执行doSomething的内容时会发生什么?
我的理解如下:
Line 1 starts and waits until the Future returned by someFutureResult1() is completed. Line 2 and Line 3 is not yet started!
Line 2 starts and waits until the Future returned by someFutureResult2() is completed
Line 3 starts and returns
Line 4 is called and returned
流量是否正确?
答案 0 :(得分:2)
这取决于你所说的“等待”,发生的事情是,与Scala阻塞线程的普通Await.result
不同,await
将其余代码包装为Future
,并释放线程以继续在async
块之外运行。