scala 使用期货和 Thread.sleep

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28160021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:51:39  来源:igfitidea点击:

Using futures and Thread.sleep

scalafuture

提问by ctamisier

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

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

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

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

If I remove Thread.sleep(2000)=> everything seems fine.

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

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

}

回答by dk14

Your await is waiting for future to complete, which is done after 2 seconds, but it doesn't wait for onSuccesshandler, 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:

您的 await 正在等待 future 完成,这会在 2 秒后完成,但它不会等待onSuccess在另一个线程中执行的处理程序(类似于 future),而是在 之后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")

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

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

exit
OK!
OK!

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

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

OK!
OK!
exit

回答by Ray Standers

Just put readLine() in your code.

只需将 readLine() 放入您的代码中。