gpt4 book ai didi

scala - 使用 future 时程序不会终止

转载 作者:行者123 更新时间:2023-12-03 23:45:51 25 4
gpt4 key购买 nike

我正在尝试对目录中的每个文件同时运行一个函数。可悲的是,每当我使用 Futures 时,我的程序都不想终止(永远运行)。我试过使用 Await.result()结果相同:/
运行代码时它执行得很好,甚至“完成?”被打印,然后它挂起......
继承人我的代码。 (我是 Scala 的新手)

val execService = Executors.newFixedThreadPool(3)
implicit val execContext = ExecutionContext.fromExecutorService(execService)

val futures = for (file <- filesList) yield Future {
println(file)
// theFunc(file)
}
val seq = Future.sequence(futures)
seq.onComplete {
case Success(x) => println("finish?")
case Failure(e) => println(e)
}

最佳答案

Executors.newFixedThreadPool引擎盖下使用 defaultThreadFactory 创建非守护线程

Returns a default thread factory used to create new threads. Thisfactory creates all new threads used by an Executor in the sameThreadGroup... Each new thread is created as a non-daemon thread


因为这些是非守护线程,所以程序不会终止。另一方面,例如, scala.concurrent.ExecutionContext.Implicits.global创建 daemon线程
val threadFactory = new DefaultThreadFactory(daemonic = true,
maxBlockers = getInt("scala.concurrent.context.maxExtraThreads", "256"),
prefix = "scala-execution-context-global",
uncaught = (thread: Thread, cause: Throwable) => reporter(cause))
我们注意到的地方 daemonic = true ,所以下面的程序会在最后终止
implicit val execContext = scala.concurrent.ExecutionContext.Implicits.global

val futures = for (file <- filesList) yield Future {
println(file)
// theFunc(file)
}
...
基于
  • https://stackoverflow.com/a/16612739/5205022
  • https://stackoverflow.com/a/28086797/5205022
  • 关于scala - 使用 future 时程序不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62884361/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com