코루틴이 실행되어야 할 스레드는 디스패쳐를 통해서 결정할 수 있습니다.

디스패처 종류

아래와 같이 3가지 개념의 디스패처를 제공합니다. (백엔드 입장에서는 default + IO 만 살펴보면 됨)

기본 디스패처 (Dispatchers.Default)

suspend fun main() = coroutineScope {
    repeat(1000) {
        launch { // or launch(Dispatchers.Default) {
            // To make it busy
            List(1000) { Random.nextLong() }.maxOrNull()
            val threadName = Thread.currentThread().name
            println("Running on thread: $threadName")
        }
    }
}
Running on thread: DefaultDispatcher-worker-9
Running on thread: DefaultDispatcher-worker-8
Running on thread: DefaultDispatcher-worker-3
Running on thread: DefaultDispatcher-worker-12
Running on thread: DefaultDispatcher-worker-11
Running on thread: DefaultDispatcher-worker-7
Running on thread: DefaultDispatcher-worker-5
Running on thread: DefaultDispatcher-worker-2
Running on thread: DefaultDispatcher-worker-9
Running on thread: DefaultDispatcher-worker-3
Running on thread: DefaultDispatcher-worker-11
Running on thread: DefaultDispatcher-worker-8
Running on thread: DefaultDispatcher-worker-

메인 디스패처 (Dispatchers.Main)

메인스레드에서 코루틴을 실행. 해당 스레드가 블로킹되는 경우 전체 애플리케이션이 멈출 수 있으므로 신중하게 사용하여야 함

fun main() = runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine and continue
        delay(1000L) // non-blocking delay for 1 second (default time unit is ms)
        log("World!") // print after delay
    }
    log("Hello") // main coroutine continues while a previous one is delayed
}

// 2023-11-21T21:51:03.717787 [main] Hello
// 2023-11-21T21:51:04.731913 [main] World!