我以为自己已经足够熟悉Kotlin协程了,直到我看到了这段代码。
1至8都被打印出来了,唯独2没有:
import kotlinx.coroutines.*
import java.lang.Runnable
import java.lang.Thread.sleep
import kotlin.concurrent.thread
fun main() {
runBlocking {
Client.createAccount()
delay(1000)
}
}
object Client: CoroutineScope {
override val coroutineContext = newSingleThreadContext("Client")
fun createAccount() = launch {
Client2.init(Runnable {
println('1')
launch {
println('2')
}
ok()
ok2()
})
println('7')
launch {
println('8')
}
}
fun ok() {
println('3')
launch {
println('4')
}
}
fun ok2() = launch {
println('5')
launch {
println('6')
}
}
}
object Client2 {
fun init(runnable: Runnable) = thread {
sleep(100)
runnable.run()
}
}
结果是:
7
8
1
3
4
5
6
回调函数中的协程永远不会被调用。为什么呢? 如果我在
createAccount()
中删除launch
,那么数字1到8都会被打印出来。
另外,如果我使用GlobalScope.launch { println('2') }
而不是launch { println('2') }
,我也可以得到数字2的输出。