问题是,作为独立的方案,如果主要读物是在工人的校对之一之前终止,你可以执行“Hello Futurecode> 印本。 (新的未来图书馆间谍系 da子)
您也可使用<代码>Await的物体(也载于scala.con Current
),等到未来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)
}
}
This can print:
Test print before future
Test print after future
Hello future!
或者,它可以根据阅读时间表印刷“Hello Future”和“以后的试验”。
同样,你也可以强迫主线等到<代码>f>上填满最后l
:
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")
}
}
Which would print:
Test print before future
Hello future!
Test print after future
然而,请注意,在您使用<代码>Await时,您将再次加以阻挡。 当然,这是为了确保你的主要应用方式不会终止,但除非另有必要,否则一般不应使用。
(The Await
object is a necessary escape hatch for situations like these, but using it throughout application code without concern for its semantics can result in slower, less-parallel execution. If you need to ensure that callbacks are executed in some specified order, for example, there are other alternatives, such as the andThen
and map
methods on Future
.)