我有以下代码:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
println("in sub coroutine ${Thread.currentThread().name}")
}
println("before coroutine in main ${Thread.currentThread().name}")
withContext(Dispatchers.IO) {
println("hello from coroutine ${Thread.currentThread().name}")
delay(1500)
println("hello from coutoutine after delay ${Thread.currentThread().name}")
}
println("after coroutine in main ${Thread.currentThread().name}")
}
Run Code Online (Sandbox Code Playgroud)
输出是:
import kotlinx.coroutines.*
fun main() = runBlocking {
launch {
println("in sub coroutine ${Thread.currentThread().name}")
}
println("before coroutine in main ${Thread.currentThread().name}")
withContext(Dispatchers.IO) {
println("hello from coroutine ${Thread.currentThread().name}")
delay(1500)
println("hello from coutoutine after delay ${Thread.currentThread().name}")
}
println("after coroutine in main ${Thread.currentThread().name}")
}
Run Code Online (Sandbox Code Playgroud)
我的理解是,withContext将代码切换到新的上下文,其中代码在不同的线程中执行,并且当前协程被挂起,直到新线程中的代码完成。但最初的定义并没有提到任何关于创建新协程的内容。
使用给定的协程上下文调用指定的挂起块,挂起直到完成,然后返回结果。
线程和协程之间不存在一一对应的关系。当协程从挂起状态恢复时,它可以在其他线程上恢复,具体取决于调度程序提供的内容。
launch并async创建新的协程。withContext不会创建新的协程,它只会改变现有协程的上下文,这就是为什么它是一个挂起函数(与launch和不同async)。
| 归档时间: |
|
| 查看次数: |
1665 次 |
| 最近记录: |