未来不完整吗? [英] The Future is not complete?

查看:83
本文介绍了未来不完整吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

object Executor extends App {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher
  import akka.stream.io._
  val file = new File("res/AdviceAnimals.tsv")
  import akka.stream.io.Implicits._
  val foreach: Future[Long] = SynchronousFileSource(file)
    .to( Sink.outputStream(()=>System.out))
    .run()

  foreach onComplete { v =>
    println(s"the foreach is ${v.get}")  // the will not be print
  }
}

但是如果我将Sink.outputStream(()=>System.out)更改为Sink.ignore,则会打印println(s"the foreach is ${v.get}").

but if I change the Sink.outputStream(()=>System.out) to Sink.ignore, the println(s"the foreach is ${v.get}") will print.

有人可以解释为什么吗?

Can somebody explain why?

推荐答案

您不是在等待流完成,而是您的main方法(Executor的主体)将完成,并且由于main方法已完成,因此退出了JVM已关闭.

You are not waiting for the stream to complete, instead, your main method (the body of Executor) will complete, and since the main method is done exits the JVM is shut down.

您想要做的是阻止该线程,并且在将来完成之前不退出应用程序.

What you want to do, is to block that thread and not exit the app before the future completes.

object Executor extends App {
  // ...your stuff with streams...
  val yourFuture: Future[Long] = ???

  val result = Await.result(yourFuture, 5 seconds)
  println(s"the foreach is ${result}")

  // stop the actor system (or it will keep the app alive)
  system.terminate()
}

这篇关于未来不完整吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆