所有
我编写了以下简单代码来测试scala.actors ._:
// java version "1.7.0_02"
// Scala code runner version 2.9.1.final
// Windows 7 Ultimate sp1 64-bit
import scala.actors._
import scala.collection.mutable.ArrayBuffer
object FutureResults extends App {
val t1 = System.currentTimeMillis
val (timeout, results) = (1000, new ArrayBuffer[Future[_]])
for (i <- 0 until 3) results += new FutureResultsActor !! "execute"
val options = Futures awaitAll (timeout, results:_*)
val t2 = System.currentTimeMillis
println("spent: %,d ms" format t2 - t1)
options foreach println
results foreach { i => println("isSet: %b" format i.isSet) }
Thread sleep timeout
val t3 = System.currentTimeMillis
println("spent: %,d ms" format t3 - t1)
options foreach println
results foreach { i => println("isSet: %b" format i.isSet) }
}
class FutureResultsActor extends Actor {
start
override def act = react { case "execute" => Futures future "done" }
}
这会产生:
spent: 1,092 ms
None
None
None
isSet: false
isSet: false
isSet: false
spent: 2,137 ms
None
None
None
isSet: false
isSet: false
isSet: false
期货的Scaladoc#awaitAll说:
The result of a future that resolved during the time span is its value wrapped in Some.
The result of a future that did not resolve during the time span is None.
超时值是否太小?好的,我将值更改为5000毫秒,然后重试:
spent: 5,070 ms
None
None
None
isSet: false
isSet: false
isSet: false
spent: 10,093 ms
None
None
None
isSet: false
isSet: false
isSet: false
全部都是无。为什么呢?......
如何从期货结果中获得一些(x)#awaitAll?
是否有错误的代码?
答案 0 :(得分:3)
确实,他们都已超时了。相当悲剧!原因是:你没有发送演员的回复 - 或者至少不正确。我不太确定“期货未来”是什么,但是......我的理解是,在演员中回答的正确方法是这样的:
class FutureResultsActor extends Actor {
start
override def act = react { case "execute" => reply("done") } // Use reply()!
}
这样做了我的结果:
spent: 150 ms
Some(done)
Some(done)
Some(done)
isSet: true
isSet: true
isSet: true
spent: 1,165 ms
Some(done)
Some(done)
Some(done)
isSet: true
isSet: true
isSet: true