You should foreach inside coroutine.
GlobalScope.launch(dispatcher) {
repeat(10) { n ->
println(n)
delay(1000L)
}
}
for more code to understand thread pool and coroutine:
val computationExecutor: Executor = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors(),
ThreadFactoryImpl("computation", Thread.MAX_PRIORITY)
)
val dispatcher = object : CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
computationExecutor.execute(block)
}
}
val t = System.currentTimeMillis()
repeat(2) { a ->
GlobalScope.launch(dispatcher) {
repeat(3) { b ->
Log.d("tag", "a: $a, b: $b, ${Thread.currentThread()}, millis: ${System.currentTimeMillis() - t}")
delay(1000L)
}
}
}
output:
a: 1, b: 0, Thread[computation-2,10,main], millis: 11
a: 0, b: 0, Thread[computation-1,10,main], millis: 13
a: 1, b: 1, Thread[computation-3,10,main], millis: 1018
a: 0, b: 1, Thread[computation-4,10,main], millis: 1021
a: 1, b: 2, Thread[computation-2,10,main], millis: 2021
a: 0, b: 2, Thread[computation-1,10,main], millis: 2023