1

Why does it print 'a' after 1 second if the thread is blocked for 3 seconds?

When a thread is blocked it can't do any computation until it is unlocked. How come is it possible to execute println('a') while this thread is blocked by Thread.sleep()?

import kotlinx.coroutines.*

fun main() = runBlocking(Dispatchers.Default) {
    GlobalScope.launch(Dispatchers.Default) {
        delay(1000L)
        println("a")
    }
    Thread.sleep(3000L)
}
1
  • Dispatchers.Default has max limit of threads same as core count of your CPU, for example if you have 4 cores, it could spawn upto 4 threads. Commented Jul 22, 2020 at 10:38

1 Answer 1

3

Default Dispatcher schedules coroutines to its own thread pool, so in your example delay(1000L) and Thread.sleep(3000L) are executed in separate threads.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.