I thought I was familiar enough with Kotlin's coroutines, until I got this code.
(我以为我对Kotlin的协程足够熟悉,直到获得此代码。)
1 to 8 are all printed except 2:
(除2以外,全部打印1至8:)
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()
}
}
The result is:
(结果是:)
7
8
1
3
4
5
6
The coroutine in callback will never be called.
(回调中的协程将永远不会被调用。)
Why? (为什么?)
And if I remove the launch
in createAccount()
the 1 to 8 will be all printed. (如果我在createAccount()
删除launch
,则将全部打印1至8。)
Also if I use GlobalScope.launch { println('2') }
instead of launch { println('2') }
, I can also get the 2 printed. (同样,如果我使用GlobalScope.launch { println('2') }
而不是launch { println('2') }
,我也可以打印出2。)
ask by sickworm translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…