appasni
02/11/2021, 1:59 PMfun main(): Unit = runBlocking {
println(1)
launch {
println(2)
launch {
println(3)
}
}
launch {
println(4)
}
println(5)
}
why does the above code print
1
5
2
4
3
instead of
1
2
3
4
5
everything is running in main thread?Niklas Gürtler
02/11/2021, 2:04 PMlaunch
are executedwasyl
02/11/2021, 2:05 PMTimo Gruen
02/11/2021, 2:05 PMlaunch
itself a suspend function?Niklas Gürtler
02/11/2021, 2:06 PMNiklas Gürtler
02/11/2021, 2:06 PMTimo Gruen
02/11/2021, 2:06 PMappasni
02/11/2021, 2:07 PMNiklas Gürtler
02/11/2021, 2:07 PMNiklas Gürtler
02/11/2021, 2:08 PMappasni
02/11/2021, 2:31 PMNiklas Gürtler
02/11/2021, 2:34 PMNiklas Gürtler
02/11/2021, 2:35 PMCasey Brooks
02/11/2021, 2:46 PMlaunch
is for starting coroutines that run in parallel. Depending on the Dispatcher, they may run on different threads, but even on a single-threaded Dispatcher the order is not guaranteed. You can think of each launch { }
as adding that block to an event queue, and whenever a thread is available to run the next job, it takes from the head of the queue.
So in this example it works like this:
1. println(1)
runs immediately and you get 1 printed
2. The first launch { }
is added to the end of the queu, but the runBlocking
block is still running so it does not execute yet
3. LIkewise, the second launch { }
block is added to the queue, after the first
4. println(5)
is now run and 5 gets printed
5. Now that the first job is finished, the next job is taken from the queue. This is the first launch
, so we get println(2)
run and 2 is printed.
6. Still inside the first launch
, the nested launch
is added to the end of the queue (which is ordered after the second launch
block)
7. The first launch
has completed, so the next job to run is the second launch block, and println(4)
is executed
8. Finally, the last job from the nested launch
is run and println(3)
is executedgildor
02/11/2021, 4:14 PMappasni
02/12/2021, 1:45 PMNiklas Gürtler
02/12/2021, 1:47 PMappasni
02/12/2021, 1:49 PMNiklas Gürtler
02/12/2021, 1:50 PMappasni
02/12/2021, 1:51 PMNiklas Gürtler
02/12/2021, 1:51 PM