【发布时间】:2021-06-01 19:55:10
【问题描述】:
我创建了一个简单的程序,在其中我使用 GlobalScope.launch 启动了 3 个协程 全部打印 100 行代码的进度,协程 1 在执行完成一半时调用挂起函数。
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
fun main(){
println("Actual Program starts here : ${Thread.currentThread().name}")
GlobalScope.launch {
println("C1 starts here : ${Thread.currentThread().name}")
for(i in 1..100){
if(i == 50){
mfunction()
}
println("C1 progress = $i : ${Thread.currentThread().name}")
}
println("C1 Ends here : ${Thread.currentThread().name}")
}
GlobalScope.launch {
println("C2 starts here : ${Thread.currentThread().name}")
for(i in 1..100){
println("C2 progress = $i : ${Thread.currentThread().name}")
}
println("C2 Ends here : ${Thread.currentThread().name}")
}
GlobalScope.launch {
println("C3 starts here : ${Thread.currentThread().name}")
for(i in 1..100){
println("C3 progress = $i : ${Thread.currentThread().name}")
}
println("C3 Ends here : ${Thread.currentThread().name}")
}
for(i in 1..100){
println("Actual Work progress = $i : ${Thread.currentThread().name}")
}
println("Actual Program Ends here : ${Thread.currentThread().name}")
}
suspend fun mfunction(){
for(i in 1..100){
println("Suspend Work progress = $i : ${Thread.currentThread().name}")
}
}
因为默认情况下主线程在那里。我的问题是,每个协程是否会创建一个新线程(为其执行)以在其上运行,或者它们都将在单个后台线程上运行??
我执行了这个程序, 我为 Coroutine1 获得 DefaultDispatcher-worker1,为 Coroutine2 获得 DefaultDispatcher-worker2,为 Coroutine3 获得 DefaultDispatcher-worker3 但有时我为所有协程获得 DefaultDispatcher-worker1。
我无法弄清楚内部发生的行为。 提前致谢。
【问题讨论】: