Kotlin 协程中的 delay() 是非阻塞函数吗?

Is delay() In Kotlin Coroutine a non-blocking function?

示例代码中的注释说 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
}

delay 是挂起和非阻塞的。

TL;DR:delay 在当前 coroutine 中执行其后的语句之前确实具有“等待”的效果。非阻塞只是意味着在此等待期间,当前 线程 可以做其他事情。


Kotlin 文档经常说挂起函数是“非阻塞”的,以明确它们不会阻塞当前线程,而是简单地挂起当前协程。

有时可能会产生误导,因为“非阻塞”强调没有任何东西被阻塞这一事实,但仍应明确挂起函数确实会挂起当前协程(因此至少 something 有点阻塞,即使线程本身继续运行也是如此。

它们挂起当前协程的事实使得这些函数从当前协程的角度来看是同步的,因为协程需要等待这些函数完成才能执行其余代码。但是,它们实际上并没有阻塞当前线程,因为它们的实现在幕后使用了异步机制。