根据文档,延迟会挂起协同线,但不会阻塞线程:
延迟是一种特殊的悬置函数。它使协同作用暂停一段特定时间。挂起协同线并不会阻塞底层线程,而是允许其他协同线程运行并将底层线程用于代码。
但是,在运行此代码时:
fun main() {
println("1")
GlobalScope.launch {
doSomething()
delay(1000L)
println("3")
}
GlobalScope.launch {
delay(1000L)
println("4")
}
println("5")
}
suspend fun doSomething() {
delay(500L)
println("2")
delay(1000L)
}所提供的产出如下:
1
5
2
4
3 根据我的理解,它应该显示为1 5 4 2 3。这是因为在第一个协同线中调用了doSomething(),因此与第二个协同线相比,延迟更多,第二个协同线是异步调用的。我的误会在哪里?
同样,在这段代码中,这两个值在2秒后一起打印:
fun main() {
GlobalScope.launch {
val value1 = doSomething1()
val value2 = doSomething2()
println(value1)
println(value2)
}
}
suspend fun doSomething1(): String {
delay(1000L)
return "This is the answer1"
}
suspend fun doSomething2(): String {
delay(1000L)
return "This is the answer2"
}为什么会这样呢?
发布于 2021-04-29 13:05:05
so the delay is more as compared to the second coroutine不,第一个延迟是:500升,第二个延迟是:1000升。
https://stackoverflow.com/questions/67317842
复制相似问题