gpt4 book ai didi

kotlin - 当主线程退出时协程会发生什么?

转载 作者:行者123 更新时间:2023-12-01 23:14:58 24 4
gpt4 key购买 nike

在 Java 中,当主线程退出时,所有用户线程(非守护线程)将继续运行,直到完成其工作。

我有一个简单的程序,它将从 1 到 5 的计数器打印到控制台。

Java 版本:

fun main(args: Array<String>) {
println("Main start")

countWithThread()

println("Main end")
}

fun countWithThread() {
Thread(Runnable {
for (i in 1..5) {
println("${Thread.currentThread().name} count $i")
Thread.sleep(10)
}
}).start()
}

输出:

Main start
Main end
Thread-0 count 1
Thread-0 count 2
Thread-0 count 3
Thread-0 count 4
Thread-0 count 5

Process finished with exit code 0

Kotlin 版本:

fun main(args: Array<String>) {
println("Main start")

countWithCoroutine()

println("Main end")
}

fun countWithCoroutine() {
launch(CommonPool) {
for (i in 1..5) {
println("${Thread.currentThread().name} count $i")
delay(10)
}
}
}

输出:

Main start
Main end

Process finished with exit code 0

可以看到,当主线程退出时,协程中的代码就不再运行了。看起来 Kotlin 会终止所有的协程。

谁能告诉我当主线程退出时协程到底发生了什么?

最佳答案

协程本身并不以 JVM 知道的方式“运行”。它们只不过是堆上的对象。

但是,协程上下文确实对何时允许 JVM 终止有发言权。创建您自己的:

val threadPool = Executors.newFixedThreadPool(4)
val dispatcher = threadPool.asCoroutineDispatcher()

现在,如果您使用它而不是 CommonPool:

launch(dispatcher) { ... }

你会发现 JVM 根本不会死,即使所有任务都完成了。仅当您明确说出时才会退出

threadPool.shutdown()

但是请注意,threadPool.shutdown() 对协程的行为与对您提交给它的“经典”任务的行为不同。执行器将确保在关闭之前完成所有提交的任务,但它不考虑挂起的协程。

关于kotlin - 当主线程退出时协程会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52196187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com