【发布时间】: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