【发布时间】:2019-08-16 06:07:28
【问题描述】:
我对此代码有疑问。
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(1000L) 替换为 Thread.sleep(1000L)。如果 GlobalScope.launch 块将在同一线程中运行,则 Thread.sleep(1000L) 将阻塞该线程。不过好像没有。
fun main() {
GlobalScope.launch { // launch new coroutine in background and continue
Thread.sleep(1000L)
println("World!")
}
println("Hello,") //
Thread.sleep(2000L) // block main thread for 2 seconds to keep JVM alive
}
【问题讨论】:
-
找到了。在这 2 个示例中,GlobalScope.launch 在不同的线程中运行。