使用期货和Thread.sleep

cta*_*ier 15 scala future

通过执行此scala代码,我在控制台中没有任何输出.(我真的不明白发生了什么)

如果我删除Console.println("Console.println OK!")=>一切似乎都很好.

如果我删除Thread.sleep(2000)=>一切似乎都很好.

你有什么想法吗?非常感谢你!

克莱门特

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)
  }

}
Run Code Online (Sandbox Code Playgroud)

dk1*_*k14 26

你的等待是等待将来完成,这是在2秒后完成的,但是它不等待onSuccess处理程序,它在另一个线程(类似于将来)中执行,但之后Await.ready(f, 60 seconds),所以进程退出的时间早于你打印的东西.要正确处理它 - 为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")
Run Code Online (Sandbox Code Playgroud)

结果Await.ready(f, ...):

exit
OK!
OK!
Run Code Online (Sandbox Code Playgroud)

结果Await.ready(f2, ...):

OK!
OK!
exit
Run Code Online (Sandbox Code Playgroud)