fun main(): Unit = runBlocking {
val job1 = launch {
delay(1_000L)
printWithThread("Hello 1")
}
val job2 = launch {
delay(1_000L)
printWithThread("Hello 2")
}
}

- 부모 코루틴을
Root Coroutine 이라 한다.
새로운 Root Coroutine 을 만들고 싶다면?: 새로운 영역(CoroutineScope )을 만들어야 한다.
fun main(): Unit = runBlocking {
val job1 = CoroutineScope(Dispatchers.Default).launch {
delay(1_000L)
printWithThread("Hello 1")
}
val job2 = CoroutineScope(Dispatchers.Default).launch {
delay(1_000L)
printWithThread("Hello 2")
}
}

launch 와 async 의 예외 발생 차이
launch : 예외가 발생하면, 예외를 출력하고 코루틴이 종료
async : 예외가 발생해도, 예외를 출력하지 않음. 예외를 확인하려면, await 이 필요함.
CoroutineExceptionHandler
fun main(): Unit = runBlocking {
val exceptionHandler = CoroutineExceptionHandler { _, exception ->
printWithThread("Caught $exception")
}
val job = CoroutineScope(Dispatchers.Default).launch(exceptionHandler) {
throw IllegalArgumentException()
}
delay(1_000L)
}
launch 에만 적용 가능하다
- 부모 코루틴이 있으면 동작하지 않는다.
코루틴 취소 예외
- 발생한 예외가
CancellationException 인 경우
- 취소로 간주하고 부모 코루틴에게 전파하지 않는다.
- 다른 예외가 발생한 경우
- 실패로 간주하고 부모 코루틴에게 전파한다.