【发布时间】:2020-08-06 14:25:30
【问题描述】:
我正在尝试理解 kotlin 中的 runBlocking。
println("before runBlocking ${Thread.currentThread().name}")
runBlocking { // but this expression blocks the main thread
delay(2000L) // non blocking
println("inside runBlocking ${Thread.currentThread().name}")
delay(2000L)
}
println("after runBlocking ${Thread.currentThread().name}")
输出
before runBlocking main
inside runBlocking main
after runBlocking main
Kotlin 说
- runBlocking -
Runs a new coroutine和blocks the current thread一直中断直到完成- 调用 runBlocking 的主线程会阻塞,直到 runBlocking 内的协程完成。
第 1 点:- 如果 runBlocking 在上面的示例中阻塞了 main 线程。然后在 runBlocking 我如何再次获得main 线程。
第 2 点:- 如果Runs a new coroutine 在上述陈述中为真,那么为什么它没有在runBlocking 内创建新的coroutine。
【问题讨论】:
-
兄弟,协程不是线程。 2. 通过
coroutineContext[CoroutineName]获取里面的协程名称, 1. 如果没有提供上下文作为参数,runBlocking 通过阻塞父线程(此处为main)在父线程上运行。