Below are two snippet, they are almost the same, except one has thread in suspend coroutine and another not.
The first code is:
suspend fun main(args: Array<String>) {
log(0)
coroutineScope {
log(1)
val result = suspendCoroutine<String> { continuation ->
log(2)
Thread {
log(3)
continuation.resume("cup")
log(4)
}.start()
}
log("5 $result")
}
log(6)
Thread.sleep(100)
}
Its output is:
[main] 0
[main] 1
[main] 2
[Thread-0] 3
[Thread-0] 5 cup
[Thread-0] 6
[Thread-0] 4
and second code is:
suspend fun main(args: Array<String>) {
log(0)
coroutineScope {
log(1)
val result = suspendCoroutine<String> { continuation ->
log(2)
// we don’t use thread in suspend coroutine
// Thread {
log(3)
continuation.resume("cup")
log(4)
// }.start()
}
log("5 $result")
}
log(6)
Thread.sleep(100)
}
Its output is:
[main] 0
[main] 1
[main] 2
[main] 3
[main] 4
[main] 5 cup
[main] 6
and the log function is:
fun <T> log(t: T) {
println("[${Thread.currentThread().name}] ${t.toString()}")
}
Why one’s output sequence is 0->1->2->3->5->6->4, and another is 0->1->2->3->4->5->6。