본문 바로가기

컴퓨터 언어/Kotlin

02. 코루틴 첫 시작

코루틴은 항상 코루틴 스코프(Coroutine Scope) 내에서 돌아가야 합니다.

이번 예제에서는 Global Scope에서 코루틴을 실행할 것입니다.

Global Scope 내에서 실행된 코루틴의 라이프사이클은 프로그램의 라이프사이클과 함께 합니다.(프로그램이 종료되면 코루틴이 종료됩니다.)

import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

fun main() {
    // 코루틴은 항상 코루틴 스코프(Coroutine Scope) 내에서 돌아가야 한다.
    // Global Scope에서 실행된 코루틴은 프로그램이 실행되는동안 계속 살아 있다.
    val startTime = System.currentTimeMillis()
    println("1 : ${System.currentTimeMillis() - startTime}")
    Thread.sleep(10  * 1000)
    println("2 : ${System.currentTimeMillis() - startTime}")

    // 새로운 스레드에서 돌아간다.
    GlobalScope.launch {
        println("4 : ${System.currentTimeMillis() - startTime}")
        // 코루틴은 일시정지를 위해 delay 함수를 사용한다.
        delay(5000)
        println("5 : ${System.currentTimeMillis() - startTime}")
        println("6 : Coroutine Thread name : ${Thread.currentThread().name}")
    }
    println("3 : ${System.currentTimeMillis() - startTime}")
    Thread.sleep(10  * 1000)
    println("7 : ${System.currentTimeMillis() - startTime}")
    println("Main Thread name : ${Thread.currentThread().name}")
}

 

더보기

[출력 결과]

1 : 0
2 : 10003
3 : 10076
4 : 10078
5 : 15086
6 : Coroutine Thread name : DefaultDispatcher-worker-1
7 : 20076
Main Thread name : main

 


delay vs sleep
delay 함수와 sleep 함수는 언뜻 보면 비슷해보이지만 실제로는 다른 역할을 합니다.
delay 함수는 코루틴 내에서만 동작하며 코루틴만 멈추지만, sleep 함수는 스레드를 멈춥니다.

 

[Thread.sleep() 사용 시 안드로이드 코드]

package com.goodee.test

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {
    private val TAG: String = "로그"

    override fun onCreate(savedInstanceState: Bundle?) {
        val startTime = System.currentTimeMillis()
        super.onCreate(savedInstanceState)

        // 1번 코루틴 
        GlobalScope.launch(context = Dispatchers.Main) {
            // 메인 스레드를 정지함.
            Thread.sleep(10 * 1000)
            Log.d(TAG,"MainActivity - 1 : ${Thread.currentThread().name} time : ${System.currentTimeMillis() - startTime}")
        }
        // 2번 코루틴
        GlobalScope.launch(context = Dispatchers.Main) {
            Log.d(TAG,"MainActivity - 2 : ${Thread.currentThread().name} time : ${System.currentTimeMillis() - startTime}")
        }
    }
}

[출력결과]

로그: MainActivity - 1 : main time : 10086
로그: MainActivity - 2 : main time : 10087

 

1번 코루틴에서 Thread.sleep() 메서드로 인해 메인스레드가 정지하여, 2번 코루틴이 실행되지 못합니다.

결국, 스레드가 깨어날 때까지 코루틴들은 모두 정지 되고 스레드가 깨어난 후에야 1번 코루틴과 2번 코루틴이 실행됩니다.

 

[delay() 사용 시 안드로이드 코드]

package com.goodee.test

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import kotlinx.coroutines.*

class MainActivity : AppCompatActivity() {
    private val TAG: String = "로그"

    override fun onCreate(savedInstanceState: Bundle?) {
        val startTime = System.currentTimeMillis()
        super.onCreate(savedInstanceState)

        // 1번 코루틴 
        GlobalScope.launch(context = Dispatchers.Main) {
            // 1번 코루틴만 정지함.
            delay(5 * 1000)
            Log.d(TAG,"MainActivity - 1 : ${Thread.currentThread().name} time : ${System.currentTimeMillis() - startTime}")
        }
        // 2번 코루틴
        GlobalScope.launch(context = Dispatchers.Main) {
            Log.d(TAG,"MainActivity - 2 : ${Thread.currentThread().name} time : ${System.currentTimeMillis() - startTime}")
        }
    }
}

 

 

[출력결과]

로그: MainActivity - 2 : main time : 46
로그: MainActivity - 1 : main time : 5047

 

1번 코루틴만 정지되므로 2번 코루틴은 그대로 실행되어 메시지를 출력하고, 1번 코루틴은 delay가 종료된 후에 실행되어 메시지를 출력합니다.

728x90
반응형

'컴퓨터 언어 > Kotlin' 카테고리의 다른 글

05. 코루틴의 runBlocking  (0) 2022.07.05
04. 코루틴의 Context  (0) 2022.07.05
03. 코루틴 suspend 함수  (0) 2022.07.05
01. 코루틴이란 무엇인가?  (0) 2022.06.27
코루틴 관련해서 좋은 블로그  (0) 2021.08.31