为什么线程混乱?
我开始学习Kotlin Coroutines。但是我面临着这样的情况。
fun main(){
println("${Thread.currentThread().name} thread started")
GlobalScope.launch {
println("${Thread.currentThread().name} thread started")
Thread.sleep(1000)
println("${Thread.currentThread().name} thread finished")
}
GlobalScope.launch {
println("${Thread.currentThread().name} thread started")
delay(1000)
println("${Thread.currentThread().name} thread finished")
}
GlobalScope.launch {
println("${Thread.currentThread().name} thread started")
delay(1000)
println("${Thread.currentThread().name} thread finished")
}
runBlocking {
delay(1000)
}
println("${Thread.currentThread().name} thread finished")
}
此代码的输出:
main thread started
DefaultDispatcher-worker-1 thread started
DefaultDispatcher-worker-2 thread started
DefaultDispatcher-worker-3 thread started
DefaultDispatcher-worker-1 thread finished
DefaultDispatcher-worker-1 thread finished
DefaultDispatcher-worker-2 thread finished
main thread finished
为什么“ DefaultDisPatcher-Worker-1线程完成”运行2次。 我想这只是线程的名称正在改变,但我想知道为什么?
i started learning kotlin Coroutines. But I am facing a situation like this.
fun main(){
println("${Thread.currentThread().name} thread started")
GlobalScope.launch {
println("${Thread.currentThread().name} thread started")
Thread.sleep(1000)
println("${Thread.currentThread().name} thread finished")
}
GlobalScope.launch {
println("${Thread.currentThread().name} thread started")
delay(1000)
println("${Thread.currentThread().name} thread finished")
}
GlobalScope.launch {
println("${Thread.currentThread().name} thread started")
delay(1000)
println("${Thread.currentThread().name} thread finished")
}
runBlocking {
delay(1000)
}
println("${Thread.currentThread().name} thread finished")
}
the output of this code:
main thread started
DefaultDispatcher-worker-1 thread started
DefaultDispatcher-worker-2 thread started
DefaultDispatcher-worker-3 thread started
DefaultDispatcher-worker-1 thread finished
DefaultDispatcher-worker-1 thread finished
DefaultDispatcher-worker-2 thread finished
main thread finished
Why "DefaultDispatcher-worker-1 thread finished" is running 2 times.
I guess it's just the threads' names are changing, but I'm wondering why ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Coroutines不能保证整个Coroutine将在整个持续时间内在同一线程上运行。线程管理由您使用的调度员处理。 dispatchers.default使用一个线程池,每次从悬架恢复时可以交换线程,就像每个
delay> delay()
调用之后一样。这是预期的行为,因为它可以减少产卵的螺纹对象的总数。Coroutines provide no guarantee that the whole coroutine will run on the same thread for its whole duration. Thread management is handled by the dispatchers you use. Dispatchers.Default uses a thread pool and can swap threads each time it resumes from suspension, as it does after each
delay()
call. This is intended behavior, as it can reduce the total number of spawned Thread objects.