I'm trying to understand runBlocking in kotlin.
println("before runBlocking ${Thread.currentThread().name}")
runBlocking { // but this expression blocks the main thread
delay(2000L) // non blocking
println("inside runBlocking ${Thread.currentThread().name}")
delay(2000L)
}
println("after runBlocking ${Thread.currentThread().name}")
Output
before runBlocking main
inside runBlocking main
after runBlocking main
Kotlin Says
- runBlocking -
Runs a new coroutine
andblocks the current thread
interruptibly until its completion- The main thread invoking runBlocking blocks until the coroutine inside runBlocking completes.
point 1 :- if runBlocking blocked the main
thread in above example. Then inside runBlocking how i get the main
thread again.
point 2 :- if Runs a new coroutine
is true in above statement, then why it didn't create new coroutine
inside runBlocking
.
coroutineContext[CoroutineName]
, 1. runBlocking runs on parent thread(in here main) by blocking it, if no context is provided as parameter. – Animesh Sahu