kotlin - 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
}
解决方案
允许您启动协程,这些GlobalScope
协程或多或少与守护线程具有相同的行为,因为它们与任何协程分离,Job
并且基本上与应用程序一样长时间运行。它们的生命周期仅受应用程序本身的限制。这是您希望通过使用“结构化并发”来避免的事情,这基本上意味着您的协程应该以一种您可以控制它们的方式嵌套,而无需手动跟踪它们的引用并加入它们以等待它们的计算。因此,在您的实际代码中,您应该尽可能避免GlobalScope
使用,因为肯定有更好的解决方案。
至于您的问题,正如已经提到的,池上的GlobalScope
运行Dispatchers.Default
,这意味着您将阻止一些工作线程,但不会阻止您从中产生协程的那个。
另一方面,如果你要写这个块:
fun main() {
runBlocking {
Thread.sleep(1000L)
println("World!")
}
println("Hello,")
Thread.sleep(2000L)
}
您会看到协程阻塞了main
线程,输出将显示不同的结果。这是因为runBlocking
在调用者线程main
而不是工作池线程之一上运行。
推荐阅读
- django - django 表单不保存更新的值
- elasticsearch - Elastic Go 找不到文档
- type-conversion - 如何在 CAPL 中将十六进制字符串转换为字节数组?
- angular - Angular canActivate 更改 URL
- ios - 更新 iTunes 应用链接的链接预览图像
- mysql - MySQL - 获取重复的连续行
- html - Vue-如何更改不同组件中相同元素的样式
- json - Spark scala 数据类型不匹配
- ios - AFNetworking responseObject 包含十六进制 - 我该如何检查?
- python - 在数据框中缺少功能的地方将 Nan 替换为 0