Using futures and Thread.sleep

霸气de小男生 提交于 2019-12-03 12:29:58

问题


By executing this scala code, I don't have any output in the console. (I don't really understand what is happening)

If I remove Console.println("Console.println OK!") => everything seems fine.

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

}

回答1:


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

Results for Await.ready(f, ...):

exit
OK!
OK!

Results for Await.ready(f2, ...):

OK!
OK!
exit



回答2:


Just put readLine() in your code.



来源:https://stackoverflow.com/questions/28160021/using-futures-and-thread-sleep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!