是否等待Scala Future块线程? [英] Does a wait on Scala Future block thread?
本文介绍了是否等待Scala Future块线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我等待获取Scala Future的结果时,它的行为是否更像接收或反应,即它会阻塞线程,还是在结果可用后安排继续?
When I wait for result of Scala Future, does it behave more like receive, or like react, i.e. does it block a thread, or schedules a continuation after result if available?
推荐答案
是的,在stdlib中,它阻塞了线程,并同步等待结果。如果要对期货应用延续传递样式,则必须使用Akka或Scalaz,它们允许直接在框中添加对期货完成的挂钩。
Yes, in stdlib it blocks the thread, and synchronously waits for results. If you want to apply continuation-passing style to futures, you'd have to use Akka or Scalaz that allow adding hooks on futures completion straight from the box.
阿卡语:
val f1 = Future { Thread.sleep(1000); "Hello" + "World" }
val f2 = f1 map { _.length }
f2 foreach println //Done asynchronously and non-blocking
与 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
这篇关于是否等待Scala Future块线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文