
동기 코드는 한 번에 하나의 작업을 처리하며, 각 작업이 완료된 후에 다음 작업을 실행runBlocking()은 비동기적인 작업을 동기적으로 실행할 수 있도록 도와주는 함수runBlocking()을 사용하여 비동기 작업을 동기적으로 실행runBlocking()은 학습 및 테스트 목적으로 사용measureTimeMillis() 함수를 사용하여 코드 블록을 실행하는 데 걸리는 시간을 측정import kotlin.system.*
import kotlinx.coroutines.*
fun main() {
val time = measureTimeMillis {
runBlocking {
println("Weather forecast")
printForecast()
printTemperature()
}
}
println("Execution time: ${time / 1000.0} seconds")
}
suspend fun printForecast() {
delay(1000)
println("Sunny")
}
suspend fun printTemperature() {
delay(1000)
println("30\u00b0C")
}
Weather forecast
Sunny
30°C
Execution time: 2.145 seconds
구조화된 동시 실행이라는 핵심 개념launch() 함수를 사용하여 새 코루틴을 실행하고 동시에 여러 작업을 실행할 수 있다import kotlin.system.*
import kotlinx.coroutines.*
fun main() {
val time = measureTimeMillis {
runBlocking {
println("Weather forecast")
launch {
printForecast()
}
launch {
printTemperature()
}
}
}
println("Execution time: ${time / 1000.0} seconds")
}
suspend fun printForecast() {
delay(1000)
println("Sunny")
}
suspend fun printTemperature() {
delay(1000)
println("30\u00b0C")
}
빠른 출력을 보여준다Weather forecast
Sunny
30°C
Execution time: 1.178 seconds

async() 함수를 사용하여 비동기 작업을 처리하고 각 작업의 결과를 Deferred 객체로 반환
await() 함수를 사용하여 각 작업의 결과에 접근하고 이를 조합하여 출력
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() {
val time = measureTimeMillis {
runBlocking {
println("Weather forecast")
val forecast: Deferred<String> = async {
getForecast()
}
val temperature: Deferred<String> = async {
getTemperature()
}
println("${forecast.await()} ${temperature.await()}")
println("Have a good day!")
}
}
println("Execution time: ${time / 1000.0} seconds")
}
suspend fun getForecast(): String {
delay(1000)
return "Sunny"
}
suspend fun getTemperature(): String {
delay(1000)
return "30\u00b0C"
}
Weather forecast
Sunny 30°C
Have a good day!
Execution time: 1.195 seconds
coroutineScope 함수를 사용하여 코루틴의 범위를 만들어 여러 동시 작업을 구조화하고 병렬로 실행coroutineScope()는 실행된 코루틴을 포함한 모든 작업이 완료된 후에만 반환package coroutinescope
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() {
val time = measureTimeMillis {
runBlocking {
println("Weather forecast")
println(getWeatherReport())
println("Have a good day!")
}
}
println("Execution time: ${time / 1000.0} seconds")
}
suspend fun getWeatherReport() = coroutineScope {
val forecast = async { getForecast() }
val temperature = async { getTemperature() }
"${forecast.await()} ${temperature.await()}"
}
suspend fun getForecast(): String {
delay(1000)
return "Sunny"
}
suspend fun getTemperature(): String {
delay(1000)
return "30\u00b0C"
}
Weather forecast
Sunny 30°C
Have a good day!
Execution time: 1.184 seconds
try-catch 블록을 사용하여 코루틴 내에서 예외를 처리package exception
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun main() {
val time = measureTimeMillis {
runBlocking {
println("Weather forecast")
println(getWeatherReport())
println("Have a good day!")
}
}
println("Execution time: ${time / 1000.0} seconds")
}
suspend fun getWeatherReport() = coroutineScope {
val forecast = async { getForecast() }
val temperature = async {
try {
getTemperature()
} catch (e: AssertionError) {
println("Caught exception $e")
"{ No temperature found }"
}
}
"${forecast.await()} ${temperature.await()}"
}
suspend fun getForecast(): String {
delay(1000)
return "Sunny"
}
suspend fun getTemperature(): String {
delay(500)
// 코드 실행 중에 예상치 못한 상황이 발생했을음 나타내는 오류
throw AssertionError("Temperature is invalid")
return "30\u00b0C"
}
Weather forecast
Caught exception java.lang.AssertionError: Temperature is invalid
Sunny { No temperature found }
Have a good day!
Execution time: 1.219 seconds
cancel() 함수를 사용하여 코루틴을 취소할 수 있다CoroutineScope 내에서 실행되며, 이를 통해 코루틴의 범위와 수명 주기를 관리하여 리소스 낭비를 방지launch() 및 async()는 CoroutineScope의 확장 함수CoroutineContext는 코루틴이 실행될 컨텍스트에 관한 정보를 제공하며, 이름, 작업, 디스패처, 예외 핸들러 등의 요소를 포함이름(코루틴을 고유하게 식별), 작업(코루틴의 수명 주기 제어), 디스패처(작업을 적절한 스레드에 전달), 예외 핸들러(예외처리)
Dispatchers.Main
- 기본 Android 스레드에서 코루틴 실행
- UI 업데이트, 상호작용에 주로 사용
Dispatchers.IO
- 기본 스레드 외부에서 디스크 또는 네트워크 I/O 실행
- 파일 읽기/쓰기, 네트워크 작업에 최적화
Dispatchers.Default
- 컨텍스트에 디스패처 지정되지 않은 경우의 기본 디스패처
- 계산이 많은 작업을 기본 스레드 외부에서 실행에 사용