【问题标题】:Coroutine runs on a dispatcher even after its thread is shutdown协程在调度程序上运行,即使它的线程被关闭
【发布时间】:2020-12-26 23:43:51
【问题描述】:

我有一个简单的 Kotlin 程序,它创建一个带有单线程的执行程序,我将它用作我的协程调度程序。

当我关闭我的执行线程时,我希望协程不会运行(或抛出异常),因为线程已终止,但这不是在第二个方法调用runMethod(singleThread) 中发生的事情:

fun main(args: Array<String>) {
    val singleThread = Executors.newSingleThreadExecutor()

    runMethod(singleThread)
    singleThread.shutdownNow()
    runBlocking {
        delay(100)
    }
    println("Shutdown status: ${singleThread.isShutdown}, terminated status: ${singleThread.isTerminated}")
    runMethod(singleThread)

    println("Program ended")
}

fun runMethod(executor: ExecutorService) {
    runBlocking {
        launch(context = executor.asCoroutineDispatcher()) {
            for (i in 1..10) {
                print("$i ")
                delay(10)
            }
        }
    }
    println("\nEnd")
}

这是这个程序的输出:

1 2 3 4 5 6 7 8 9 10 
End
Shutdown status: true, terminated status: true
1 2 3 4 5 6 7 8 9 10 
End
Program ended

Process finished with exit code 0

【问题讨论】:

    标签: kotlin threadpool executorservice kotlin-coroutines


    【解决方案1】:

    如果我不得不猜测这可能是因为唯一使用的挂起函数是delay。由于Executors.newSingleThreadExecutor() 不是ScheduledExecutorService,它必须依赖回退机制来调度延迟调用,这可能导致它永远不会实际使用提供的Executor,而是始终使用runBlocking 或@987654326 提供的执行程序@(delay 后备)。

    确保检查协程中的Thread.currentThread() 以查看代码当前执行的位置。

    【讨论】:

    • 我认为你是对的,看起来它第二次在默认执行器上运行:“kotlinx.coroutines.DefaultExecutor”。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    • 2011-01-27
    • 2012-05-08
    • 1970-01-01
    相关资源
    最近更新 更多