在Kotlin Coroutine中,delay()是非阻塞函数吗?

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

示例代码中的注释说delay()是非阻塞的。 应该暂停吗?

https://kotlinlang.org/docs/reference/coroutines/basics.html

1
2
3
4
5
6
7
8
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
}


Kotlin文档经常对挂起函数说"非阻塞",以表明它们不会阻塞当前线程,而只是挂起当前协程。

是的,delay正在挂起且未阻塞。

有时可能会产生误导,因为"非阻塞"强调没有阻塞的事实,同时仍应明确指出,挂起函数确实会挂起当前的协程(因此至少有一些被阻塞,即使线程 本身进行下去)。

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