首页 > 解决方案 > 为什么带有 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,那么它会很快完成。

为什么这段代码没有结束?

标签: kotlinkotlin-coroutines

解决方案


原因是非守护线程使 JVM 保持活动状态。

您需要关闭您ExecutorService的 JVM 才能正确地让 JVM 完成其执行。

这已在此处得到解答: ExecutorService JVM 不会终止


推荐阅读