使用期货和Thread.sleep [英] Using futures and Thread.sleep
问题描述
通过执行此Scala代码,控制台中没有任何输出. (我不太了解发生了什么事
By executing this scala code, I don't have any output in the console. (I don't really understand what is happening)
如果我删除Console.println("Console.println OK!")
=>一切都很好.
If I remove Console.println("Console.println OK!")
=> everything seems fine.
如果我删除Thread.sleep(2000)
=>一切似乎都很好.
If I remove Thread.sleep(2000)
=> everything seems fine.
您对此有任何想法吗?非常感谢你!
Do you have any ideas about this ? Thank you very much!
Clément
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.{Await, Future}
import scala.language.postfixOps
object ScalaFuture {
def main(args: Array[String]) {
val f: Future[String] = Future {
Thread.sleep(2000)
"future value"
}
f.onSuccess {
case s => {
Console.println("Console.println OK!")
System.out.println("System.out.println OK!")
}
}
Await.ready(f, 60 seconds)
}
}
推荐答案
您的等待正在等待将来完成,这在2秒后完成,但是它不等待onSuccess
处理程序,该处理程序在另一个线程中执行(与将来类似),但是在Await.ready(f, 60 seconds)
之后,因此进程比您打印某些内容更早退出.要正确处理它-为onComplete
创建新的未来:
Your await is waiting for future to complete, which is done after 2 seconds, but it doesn't wait for onSuccess
handler, which executes in another thread (similar to future), but after Await.ready(f, 60 seconds)
, so process exits earlier than you print something. To process it correctly - create new future for onComplete
:
val f: Future[String] = Future {
Thread.sleep(2000)
"future value"
}
val f2 = f map { s =>
println("OK!")
println("OK!")
}
Await.ready(f2, 60 seconds)
println("exit")
Await.ready(f, ...)
的结果:
exit
OK!
OK!
Await.ready(f2, ...)
的结果:
OK!
OK!
exit
这篇关于使用期货和Thread.sleep的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!