Just started learning Kotlin and I am trying to make sense of the output of the code snippet below. Per my understanding, the output should be in this order -
Right After Thread.sleep call - from main thread
mainline - from main thread
launched in new thread - from pool-1-thread-1 thread
- The first coroutine is created and passed to new thread for execution and suspend for 2 secs.
- Second coroutine is launched in main thread. Block the main thread for 0.5 sec and print.
- Main thread get unblocked, and third print statement is executed.
- Lastly, the first coroutine resume execution after 2 secs delay and prints the statement.
However, the actual result printed is -
launched in new thread - from pool-1-thread-1 thread
mainline - from main thread
Right After Thread.sleep call - from main thread
Greatly appreciate if someone could help me understand the logic behind it
fun main() = runBlocking {
val es = Executors.newSingleThreadExecutor()
withContext (es.asCoroutineDispatcher()) {
delay(2000L)
println("launched in new thread - from ${Thread.currentThread().name} thread")
}
launch {
Thread.sleep(500L)
println("Right After Thread.sleep call - from ${Thread.currentThread().name} thread")
}
println("mainline - from ${Thread.currentThread().name} thread")
es.shutdown()
}