首页 > 解决方案 > Does GlobalScope.launch create a new thread or run in the same thread?

问题描述

I have the question from this code.

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
}

I replace delay(1000L) with Thread.sleep(1000L). If GlobalScope.launch block will run in the same thread, the Thread.sleep(1000L) will block the thread. However it seems not.

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
} 

标签: kotlinkotlin-coroutines

解决方案


允许您启动协程,这些GlobalScope协程或多或少与守护线程具有相同的行为,因为它们与任何协程分离,Job并且基本上与应用程序一样长时间运行。它们的生命周期仅受应用程序本身的限制。这是您希望通过使用“结构化并发”来避免的事情,这基本上意味着您的协程应该以一种您可以控制它们的方式嵌套,而无需手动跟踪它们的引用并加入它们以等待它们的计算。因此,在您的实际代码中,您应该尽可能避免GlobalScope使用,因为肯定有更好的解决方案。

至于您的问题,正如已经提到的,池上的GlobalScope运行Dispatchers.Default,这意味着您将阻止一些工作线程,但不会阻止您从中产生协程的那个。

另一方面,如果你要写这个块:

fun main() {
    runBlocking { 
        Thread.sleep(1000L) 
        println("World!") 
    }
    println("Hello,") 
    Thread.sleep(2000L) 
}

您会看到协程阻塞了main线程,输出将显示不同的结果。这是因为runBlocking在调用者线程main而不是工作池线程之一上运行。


推荐阅读