use*_*721 0 kotlin kotlin-coroutines
示例代码中的注释说 delay() 是非阻塞的。应该暂停吗?
https://kotlinlang.org/docs/reference/coroutines/basics.html
fun main() {
GlobalScope.launch { // launch new coroutine in background and continue
delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
println("World!") // print after delay
}
println("Hello,") // main thread continues while coroutine is delayed
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
Run Code Online (Sandbox Code Playgroud)
delay 正在暂停和非阻塞。
TL;DR:delay在执行当前协程中紧随其后的语句之前确实具有“等待”的效果。非阻塞只是意味着在此等待期间,当前线程可以做其他事情。
Kotlin 文档经常说“非阻塞”用于挂起函数,以明确它们不会阻塞当前线程,而是简单地挂起当前协程。
有时可能会产生误导,因为“非阻塞”强调没有被阻塞的事实,而仍然应该明确挂起函数确实挂起当前协程(所以至少有些东西被阻塞了,即使线程本身进行)。
它们挂起当前协程的事实使这些函数从当前协程的角度来看是同步的,因为协程需要等待这些函数完成才能执行其余代码。然而,它们实际上并没有阻塞当前线程,因为它们的实现在幕后使用了异步机制。
| 归档时间: |
|
| 查看次数: |
2280 次 |
| 最近记录: |