kotlin - 为什么带有 newSingleThreadExecutor 的 runBlocking 块不结束?
问题描述
我试图弄清楚为什么这段代码我会无限运行:
fun main() = runBlocking {
launch {
delay(200L)
println("Task from runBlocking $coroutineContext")
}
// coroutineScope { // if I uncomment this line and comment next line, then it will finish
CoroutineScope(Executors.newSingleThreadExecutor().asCoroutineDispatcher()).launch {
launch {
delay(500L)
println("Task from nested launch $coroutineContext")
}
delay(100L)
println("Task from coroutine scope $coroutineContext")
}
println("Coroutine scope is over")
}
当我运行这段代码时,我看到了这个输出:
Coroutine scope is over
Task from coroutine scope [StandaloneCoroutine{Active}@5287ba83, java.util.concurrent.Executors$FinalizableDelegatedExecutorService@91445f6]
Task from runBlocking [StandaloneCoroutine{Active}@28ac3dc3, BlockingEventLoop@32eebfca]
Task from nested launch [StandaloneCoroutine{Active}@702cf19c, java.util.concurrent.Executors$FinalizableDelegatedExecutorService@91445f6]
但程序永远不会结束......正如我在评论中所写,如果我newSingleThreadExecutor
只用一个简单的替换 line coroutineScope
,那么它会很快完成。
为什么这段代码没有结束?
解决方案
原因是非守护线程使 JVM 保持活动状态。
您需要关闭您ExecutorService
的 JVM 才能正确地让 JVM 完成其执行。
这已在此处得到解答: ExecutorService JVM 不会终止
推荐阅读
- vb.net - 无法打开 PDF。某些东西使此 PDF 无法打开。使用 VB.NET 打印表单
- java - 具有用户特定功能的 JSF webapp
- scala - Spark agg 为多列收集单个列表
- java - 无法从 SQLite 获取要删除的 RecyclerView 项目位置
- pointers - 我不知道当它是一个常量时我应该如何初始化一个变量
- rpa - ui path rpa 无法将 excel 抓取的数据转换为 pdf 格式
- c# - .NET Core 2.x 中与 HostBuilder 的简单注入器集成
- python - 在 Python 中大范围绘制 3D 数据的最佳方法
- linux - 使用 egrep 匹配和文件名创建文件
- c# - 查看执行程序调用的dll