我目前正在編寫擴展Future伴侶對象的代碼。一個功能我想實現是Any
Scala Future和Thread.sleep的奇怪行爲
//returns the future that computes the first value computed from the list. If the first one fails, fail.
def any[T](fs: List[Future[T]]): Future[T] = {
val p = Promise[T]()
fs foreach { f => {
f onComplete {
case Success(v) => p trySuccess v
case Failure(e) => p tryFailure e
}
} }
p.future
}
我試着用
test("A list of Futures return only the first computed value") {
val nums = (0 until 10).toList
val futures =
nums map { n => Future { Thread.sleep(n*1000); n } }
val v = Await.result(Future.any(futures), Duration.Inf)
assert(v === 0)
}
但返回的值是1,不是0。當我切換休眠時間n*1000
到(n+1)*1000
,它來測試我的代碼工作正常(返回0)。
0上調用睡眠有什麼特別效果嗎?
哦,我忘了添加'blocking'塊。我錯過了這些線程在執行上下文中運行。您的解決方案完全正常。謝謝。 –