The issue is that you're executing that as a standalone program, whose main thread is terminating before one of the worker threads can execute the "Hello future!" println
. (The threads that the new futures library spawns are daemon threads).
You can also use the Await
object (also in scala.concurrent
) to wait until the future f
is completed:
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!
Or, it can print "Hello future!" before "Test print after future" depending on the thread schedule.
Likewise, you can force the main thread to wait until f
is completed before the last println
as follows:
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
However, note that when you use Await
, you're blocking. This of course makes sense to make sure that your main application thread doesn't terminate, but generally shouldn't be used unless necessary otherwise.
(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
.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…