코드
fun main() {
runBlocking {
println("Weather forecast")
launch {
printForecast()
}
launch {
printTemperature()
}
println("Have a good day!")
}
}
suspend fun printForecast() {
delay(1000)
println("Sunny")
}
suspend fun printTemperature() {
delay(1000)
println("30\u00b0C")
}
결과
Weather forecast
Have a good day!
Sunny
30°C
💡 병렬 분해
- 문제를 병렬로 해결할 수 있는 더 작은 하위 태스크로 세분화하는 것
- 하위 태스크의 결과가 준비되면 최종 결과로 결합
fun main() { runBlocking { println("Weather forecast") println(getWeatherReport()) println("Have a good day!") } } 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" }
코드
fun main() {
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!")
}
}
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!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleScope.launch(Dispatchers.IO) {
delay(3000)
Log.d(TAG, "코루틴 1: ${Thread.currentThread().name}")
withContext(Dispatchers.Main) {
Log.d(TAG, "코루틴 2: ${Thread.currentThread().name}")
}
}
Log.d(TAG, "onCreate: ${Thread.currentThread().name}")
}
