Kotlin - Achieving Executors.newSingleThreadExecutor behaviour using coroutines
Executors.newSingleThreadExecutor queues the tasks registered to it and then executes them sequentially. The following code:
val singleThreadedExecutor = Executors.newSingleThreadExecutor()
(0..10).forEach { i ->
singleThreadedExecutor.execute {
if (i % 2 == 0) {
Thread.sleep(2000)
} else {
Thread.sleep(1000)
}
println(i)
}
}
outputs this:
I/System.out: 0
I/System.out: 1
I/System.out: 2
I/System.out: 3
I/System.out: 4...