[英]CoroutineScope Questions
在 Coroutine Scope 上,為什么先調用 launch 塊時先調用最后一個 println()?
海傑·布賴恩·李,
在runBlocking
中,您可以在調用launch{}
時啟動兩個新的協程,而不會阻塞當前線程。 所以runBlocking
中的塊繼續執行並且println
s被執行。
如果您希望launch
塊首先完成,您必須通過在其Job
上使用.join()
讓您的線程等待其執行
runBlocking {
val job = launch {
println("launch : ${Thread.currentThread() .name}")
println("launch 1")
}
job.join()
println("runBlocking: ${Thread. currentThread () .name}")
println("runBlockging")
}
鏈接: https ://kotlinlang.org/docs/coroutines-basics.html#an-explicit-job
Launch 是一個協程構建器。 它與其余代碼同時啟動一個新的協程,該協程繼續獨立工作。 這就是為什么首先執行和打印外部代碼的原因。
嘗試使用 coroutineScope 的掛起功能
使用掛起功能
參考這里。 在 kotlin 文檔中提到https://kotlinlang.org/docs/coroutines-basics.html#scope-builder
fun main() = runBlocking{
doWork()
}
fun doWork() = coroutineScope{
launch{
//your code here
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.