println無論我是否更改delay兩個 doXX 函式中的值,總是列印 3 秒。兩個doXX函式都只需要2秒,為什么結果總是3
我認為所有三個協程都同時運行,所以我增加了最后一個協程的延遲以等待前兩個協程完成。然后我列印變數的值time。這是代碼。
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
launch { doSomethingUsefulOne() }
launch { doSomethingUsefulTwo() }
}
launch {
delay(6000)
println("Completed in $time ms")
}
}
suspend fun doSomethingUsefulOne() {
delay(1000L)
}
suspend fun doSomethingUsefulTwo(){
delay(1000L)
}
如果我將它們放在 runBlocking 范圍的子范圍中,結果總是正確的。也就是大約 2 秒。
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
doWorld
}
launch {
delay(4000)
println("Completed in $time ms")
}
}
suspend fun doWorld() = coroutineScope { // this: CoroutineScope
launch {
delay(2000L)
println("World 2")
}
launch {
delay(1000L)
println("World 1")
}
println("Hello")
}
uj5u.com熱心網友回復:
檢查檔案。頂部的示例與您的非常相似,應該闡明這一點以及協程的其他方面。
問題是launch 啟動一個新的協程并繼續。measureTimeMillis啟動 2 個協程并繼續執行后的塊;這需要 3ms 才能運行。值 3 存盤在time其中,這就是第三個協程列印的內容。
uj5u.com熱心網友回復:
你剛剛發現了協程的一個特性。它們并行運行。讓我們看一下代碼:
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
launch { doSomethingUsefulOne() } // Launches first coroutine does NOT wait
launch { doSomethingUsefulTwo() } // Launches second coroutine does NOT wait
} // This block is finished in 3ms, because it only launches the coroutines
launch {
delay(6000)
println("Completed in $time ms")
}
}
如果您想等待兩個協程完成,可以將它們包裝在coroutineScopeor中runBlocking:
fun main() = runBlocking<Unit> {
val time = measureTimeMillis {
runBlocking { // waits for all contained coroutines to finish
launch { doSomethingUsefulOne() } // Launches first coroutine does NOT wait
launch { doSomethingUsefulTwo() } // Launches second coroutine does NOT wait
}
}
launch {
delay(6000)
println("Completed in $time ms")
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/524323.html
標籤:科特林协程
上一篇:如何遮蓋影像的特定區域并創建帶有遮罩部分為白色的黑色背景影像
下一篇:將證書字串拆分為兩個單獨的證書
