我不明白为什么在下面的程序中GlobalScope.launch
指令没有完成它的任务。
我确实理解它runBlocking
无法控制GlobalScope
并且使用它通常很糟糕,但这并不让我知道为什么里面的指令GlobalScope.launch {}
没有按预期执行。
代码片段:
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
实际输出:
一个空文件。