gpt4 book ai didi

kotlin - 为什么 runBlocking 没有阻塞调用线程

转载 作者:行者123 更新时间:2023-12-02 12:34:40 24 4
gpt4 key购买 nike

我想了解 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 Says

  1. runBlocking - Runs a new coroutine and blocks the current thread interruptibly until its completion
  2. The main thread invoking runBlocking blocks until the coroutine inside runBlocking completes.

第 1 点:- 如果 runBlocking 阻止了 main上面例子中的线程。然后在 runBlocking 中我如何获得 main再次线程。

第 2 点:- 如果 Runs a new coroutine在上面的陈述中是真的,那么为什么它没有创建新的 coroutine里面runBlocking .

最佳答案

runBlocking ( doc ) 的签名是

fun <T> runBlocking(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> T
): T (source)

如果您看到 context 参数,它默认为 EmptyCoroutineContext。因此,当您不传递特定上下文时,默认值是当前线程上的事件循环。由于运行 runBlocking block 之前的当前线程是主线程,因此无论您在该 block 内运行什么,都仍在主线程上。

如果你像下面这样传递协程上下文,你就会让 runBlocking 中的 block 在不同的线程中运行。

println("before runBlocking ${Thread.currentThread().name}")

runBlocking(Dispatchers.Default) {
delay(2000L)
println("inside runBlocking ${Thread.currentThread().name}")
delay(2000L)
}

println("after runBlocking ${Thread.currentThread().name}")

输出

before runBlocking main
inside runBlocking DefaultDispatcher-worker-1
after runBlocking main

或者,如果您在不传递上下文的情况下启动 runBlocking,但如下所示在内部启动协程,您会看到它在不同的线程上运行。

println("before runBlocking ${Thread.currentThread().name}")

runBlocking {
println("inside runBlocking ${Thread.currentThread().name}")
delay(2000L)
CoroutineScope(Dispatchers.Default).launch {
println("inside runBlocking coroutineScope ${Thread.currentThread().name}")
}
delay(2000L)
}

println("after runBlocking ${Thread.currentThread().name}")

输出

before runBlocking main
inside runBlocking main
inside runBlocking coroutineScope DefaultDispatcher-worker-1
after runBlocking main

关于kotlin - 为什么 runBlocking 没有阻塞调用线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61384220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com