muralimohan962
11/01/2024, 3:40 AMimport kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicInteger
@OptIn(DelicateCoroutinesApi::class)
val scope = CoroutineScope(newFixedThreadPoolContext(Runtime.getRuntime().availableProcessors(), "Background workers"))
var count = AtomicInteger(0)
fun main() {
runBlocking {
repeat(50_000) {
scope.launch() {
delay(5000)
println(count.incrementAndGet())
}
}
}
println("Done!")
}
Why does “Done!” get printed earlier than “count” value? I want “Done!” to be printed only after completing code inside runBlocking. What’s wrong with my code? Thanks in advance.Zach Klippenstein (he/him) [MOD]
11/01/2024, 3:44 AMmuralimohan962
11/01/2024, 4:10 AM