我正在尝试对目录中的每个文件同时运行一个函数。可悲的是,每当我使用 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. This factory creates all new threads used by an Executor in the same ThreadGroup... 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)
}
...
基于关于scala - 使用 future 时程序不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62884361/