Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
import kotlinx.coroutines.*
suspend fun work(name: String, ms: Long, result: Int): Int {
delay(ms)
println(name)
return result
}
fun main() = runBlocking {
val a = async { work("a", 200, 1) }
val b = async { work("b", 100, 2) }
println(a.await() + b.await())
}b a 3
- Expecting
a b 3: thinking the coroutine started or awaited first finishes first. Both wait at the same time, so the shorter delay ofbends first. - Expecting the sum before the letters: thinking
await()returns at once. It suspendsmainuntil that block has finished and printed its letter.
- About how long does the whole program take, and why not 300 ms?
- What changes if
b.await()is written beforea.await()?