hi everyone. total n00b question here. all help gratefully received. 🙏
i've got this code, which is based on one of the examples from the
kotlinlang.org docs:
fun main() = runBlocking {
launch {
println("block 1: start")
delay(2000)
println("block 1: end")
}
launch {
println("block 2: start")
delay(1000)
println("block 2: end")
}
Unit
}
as expected, the output is:
block 1: start
block 2: start
block 2: end
block 1: end
so the two
launch
blocks are running concurrently.
next i try and replace the
delay
calls with some functions of my own:
fun functionThatTakesALongTime() {
for (j in 1..5) {
for (i in 1..1_000_000_000) {
i * i * i
}
}
}
fun functionThatTakesAShortTime() {
1 + 1
}
fun main() = runBlocking {
launch {
println("block 1: start")
functionThatTakesALongTime()
println("block 1: end")
}
launch {
println("block 2: start")
functionThatTakesAShortTime()
println("block 2: end")
}
Unit
}
this time the output is this:
block 1: start
block 1: end
block 2: start
block 2: end
in other words it ran the whole of the first
launch
block before starting on the second one. want i want is for them to run concurrently as in the first example.
i guess there's something fundamental that i'm missing! what is it about
delay
which enables the
launch
blocks to run concurrently?
thanks!