【发布时间】:2020-12-09 10:35:06
【问题描述】:
我不明白为什么在下面的程序中GlobalScope.launch 指令没有完成它的任务。
我明白runBlocking 无法控制GlobalScope,而且使用它通常很糟糕,但这并不让我知道为什么GlobalScope.launch {} 中的指令没有按预期执行。
代码sn-p:
package coroutines
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.io.File
fun main() = runBlocking<Unit> {
GlobalScope.launch {
val file = File(javaClass.getResource("/coroutines_file.txt").path)
file.printWriter().use { out ->
repeat(10) { i ->
delay(100)
out.println(i.toString())
}
}
}
}
coroutines_file 中的预期输出:
0
1
2
3
4
5
6
7
8
9
实际输出:
一个空文件。
【问题讨论】:
-
Global coroutines are like daemon threads。
.join()它,如果你想等待它完成。
标签: kotlin kotlin-coroutines terminate file-writing global-scope