When I wait对于 Scala Future 的结果,它的行为是否更像receive,或者像react,即它是否会阻塞线程,或者在结果可用时安排继续操作?
是的,在 stdlib 中它会阻塞线程,并同步等待结果。如果你想对 futures 应用连续传递风格,你必须使用 Akka 或 Scalaz,它们允许直接从盒子里添加有关 futures 完成的钩子。
Akka http://doc.akka.io/futures-scala:
val f1 = Future { Thread.sleep(1000); "Hello" + "World" }
val f2 = f1 map { _.length }
f2 foreach println //Done asynchronously and non-blocking
与相同Scalaz http://code.google.com/p/scalaz/:
scala> val f1 = promise {Thread.sleep(1000); "Hello" + "World"}
f1: scalaz.concurrent.Promise[java.lang.String] = scalaz.concurrent.Promise$$anon$1@1f7480
scala> val f2 = f1 map{str => str.length}
f2: scalaz.concurrent.Promise[Int] = scalaz.concurrent.Promise$$anon$1@1d40442
scala> f2.map(println)
10
res5: scalaz.concurrent.Promise[Unit] = scalaz.concurrent.Promise$$anon$1@116ad20
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)