카테고리 없음

[Coroutine] Job 객체에 대해서 정리

Gemstone 2022. 6. 23. 18:13

코루틴 빌더 launch는 Job 객체를 반환하고, 이를 통해 종료가 될 때까지 기다릴 수 있습니다.

바로 join() 함수를 사용!

 

import kotlinx.coroutines.*

suspend fun doOneTwoThree() = coroutineScope {
    val job = launch {
        println("launch1: ${Thread.currentThread().name}")
        delay(1000L) // suspension point
        println("3!")
    }
    job.join() // join은 기다리게 하는 것. // suspension point // 원래는 delay(1000L) 호출되면 양보를 해야하는데
    // join이 있기때문에 기다리게 된다.

    // 순서를 잡은 것이지 바로 수행하도록 한 건 아니기 때문에 4가 먼저 출력된다.
    launch {
        println("launch2: ${Thread.currentThread().name}")
        println("1!")
    }

    launch {
        println("launch3: ${Thread.currentThread().name}")
        delay(500L) // suspension point
        println("2!")  
    }
    
    println("4!")
}

fun main() = runBlocking {
    doOneTwoThree()
    println("runBlocking: ${Thread.currentThread().name}")
    println("5!")
}

 

출력결과

요약 : 부모 코루틴은 자식 코루틴이 다 처리될 때까지 끝나지 않는다.

join이 있으면 무조건 멈추고 기다리고, 부모는 자식을 버리지 않는다.

 

 

코루틴은 협력적으로 동작하기 때문에 여러 코루틴을 만드는 것이 큰 비용이 들지 않습니다. 10만개의 간단한 일을 하는 코루틴도 큰 부담은 아닙니다. 

 

import kotlinx.coroutines.*

suspend fun doOneTwoThree() = coroutineScope {
    val job = launch {
        println("launch1: ${Thread.currentThread().name}")
        delay(1000L)
        println("3!")
    }
    job.join()

    launch {
        println("launch2: ${Thread.currentThread().name}")
        println("1!")
    }

    repeat(1000) {
        launch {
            println("launch3: ${Thread.currentThread().name}")
            delay(500L)
            println("2!")  
        }
    }
    println("4!")
}

fun main() = runBlocking {
    doOneTwoThree()
    println("runBlocking: ${Thread.currentThread().name}")
    println("5!")
}

 

10만개를 쓰레드로 만들면 되게 어려운 일일텐데 코루틴은 가볍기 때문에 가능하다!