gpt4 book ai didi

kotlin 协程的执行优先级

转载 作者:行者123 更新时间:2023-12-02 13:30:52 25 4
gpt4 key购买 nike

我需要帮助理解以下 2 段代码的结果

第一个片段

fun main() = runBlocking { 
launch {
println("Task from runBlocking")
}

coroutineScope {
launch {
println("Task from nested launch")
}

println("Task from coroutine scope")
}

println("Coroutine scope is over")
}

而且,第二个片段
fun main() = runBlocking { 
launch {
println("Task from runBlocking")
}

println("Coroutine scope is over")
}

第一个片段的结果是:
Task from coroutine scope
Task from runBlocking
Task from nested launch
Coroutine scope is over

第二个片段的结果是:
Coroutine scope is over
Task from runBlocking

所以,问题是为什么这些语句按这个顺序打印?

最佳答案

对于 1st snippet您正在使用 coroutineScope正如您从 documentation 中看到的那样定义为 suspend函数,所以它阻塞了当前线程和 "Coroutine scope is over"直到 coroutineScope 才打印块已完成。

对于 2nd snippet字符串 "Coroutine scope is over"印在 "Task from run blocking" 之前因为它的 println 是在主线程中执行的,而 launch它在工作线程中运行尚未完成其工作。

fun mainOne() = runBlocking {
launch {
println("Task from runBlocking")
}

// coroutineScope is defined as a suspend function, so it's blocking the current thread
coroutineScope {

launch {
// worker thread, slower than main thread, printed after "Task from coroutine scope"
println("Task from nested launch")
}
// main thread, printed before "Task from nested launch" within CoroutineScope
println("Task from coroutine scope")
}

// main thread is now free to run and it prints the string below
println("Coroutine scope is over")
}


fun mainTwo() = runBlocking {
launch {
// worker thread, slower than main thread, printed after "Coroutine scope is over" due to concurrency
println("Task from runBlocking")
}
// main thread is running and prints the string below before launch job has finished.
// If you put a delay here you'll notice that launch job gets completed before "Coroutine scope is over"
// E.g delay(2000)
println("Coroutine scope is over")
}

希望这是有道理的:)

关于kotlin 协程的执行优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61406005/

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