Scala:无法获取Future结果

pftdvrlh  于 2023-03-18  发布在  Scala
关注(0)|答案(1)|浏览(166)

我尝试在Intellij Idea中运行一个简单的Future示例:

import scala.concurrent.ExecutionContext.Implicits.global
object Futures1 extends App {
        val f = Future {
                Thread.sleep(500)
                1 + 1
               }
        f map println
        Thread.sleep(5)
}

而且它还没有完成。正如我所想,由于threadPool中主线程和线程之间的竞争。
我试着治疗它,通过:
1.申请等待:

Await.result(f map println, Duration(5, SECONDS))

1.自定义用于关闭守护进程线程的执行上下文:

class MyExecutionContext extends ExecutionContext {
          override def execute(runnable:Runnable) = {
             val t = new Thread(runnable)
             t.setDaemon(false)
             t.start()
            }
          override def reportFailure(t:Throwable) = t.printStackTrace
 }

 implicit lazy val context: ExecutionContext = new MyExecutionContext

但无济于事。
还能有什么别的办法?

5fjcxozz

5fjcxozz1#

问题是f map println产生了一个新的未来?
如果你说println(Await.result(f, Duration(5, SECONDS)))
您的代码工作并打印输出2。

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent._
import scala.concurrent.duration._

val f = Future {
    println("running future")
    1 + 1
}

println("maybe runs ahead or behind the future...")

println(Await.result(f, Duration(5, SECONDS)))

println("app finished")

相关问题