问题是您将其作为独立程序执行,其主线程在其中一个工作线程可以执行“Hello future!”之前终止。println
. (新的期货库产生的线程是守护线程)。
您还可以使用Await
对象(也在 中scala.concurrent
)等到未来f
完成:
import scala.concurrent._
import scala.concurrent.util._
object Test {
def main(args: Array[String]) {
println("Test print before future")
val s = "Hello"
val f = future {s + " future!"}
f onSuccess {case v => println(v)}
println("Test print after future")
Await.ready(f, Duration.Inf)
}
}
这可以打印:
Test print before future
Test print after future
Hello future!
或者,它可以打印“Hello future!” 在“未来之后的测试打印”之前,具体取决于线程调度。
同样,您可以强制主线程等到f
最后一个完成之前println
,如下所示:
import scala.concurrent._
import scala.concurrent.util._
object Test {
def main(args: Array[String]) {
println("Test print before future")
val s = "Hello"
val f = future {s + " future!"}
f onSuccess {case v => println(v)}
Await.ready(f, Duration.Inf)
println("Test print after future")
}
}
哪个会打印:
Test print before future
Hello future!
Test print after future
但是,请注意,当您使用 时Await
,您是在阻塞。这当然可以确保您的主应用程序线程不会终止,但除非另有必要,否则通常不应使用。
(Await
对于此类情况,该对象是必要的逃生舱口,但在整个应用程序代码中使用它而不考虑其语义可能会导致更慢、更少并行执行。例如,如果您需要确保回调以某些指定的顺序执行, ,还有其他替代方法,例如andThen
和map
上的方法Future
。)