Dev_TIMI

[Kotlin] Coroutine 디버깅 옵션

by its_TIMI

 

 

VM options에 다음과 같이 입력하면

 

fun printWithThread(str: Any?) {
    println("[${Thread.currentThread().name}] $str")
}

 

 

이와 같은 함수를 활용하여

 

package coroutine

import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield

fun main(): Unit =
    runBlocking { // 일반루틴 세계와 코루틴 세계를 연결한다. 이 함수 자체로 새로운 코루틴을 만든다
        printWithThread("START")
        launch { // 반환값이 없는 코루틴을 만든다
            // 만들어지자마자 실행되지는 않는다. runBlocking이 끝나면 실행된다.
            newRoutine()
        }
        yield()
        printWithThread("END")
}

suspend fun newRoutine() { // suspend fun이 붙은 다른 함수를 호출할 수 있다.
    val num1 = 1
    val num2 = 2
    yield()     // suspend fun 함수
    // 현재 코루틴을 일시 중단하고 다른 코루틴에게 실행을(순서를, 스레드를) 양보한다.
    printWithThread("${num1 + num2}")
}

 

 

쓰레드 이름을 프린트 할 때 기존에 해당 옵션을 주지 않았을 때는 이와같이 

[main] START
[main] END
[main] 3

Process finished with exit code 0

Main만 나오다가 

 

 

이와같이 코루틴 번호까지 나오게 된다.

[main @coroutine#1] START
[main @coroutine#1] END
[main @coroutine#2] 3

Process finished with exit code 0

 

 

출처: 최태현 센세의 2시간으로 끝내는 코루틴 강의 at Inflearn

반응형

'Kotlin' 카테고리의 다른 글

[Kotlin] Coroutine - Structured Concurrency  (0) 2024.01.12
[Kotlin] Coroutine의 예외처리  (0) 2024.01.12
[Kotlin] Coroutine - 취소  (0) 2024.01.11
[Kotlin] Coroutine - async()  (1) 2024.01.09
람다 그리고 코틀린  (0) 2023.12.20

블로그의 정보

Dev_TIMI

its_TIMI

활동하기