• Kotlinのコルーチンについて Webサイトには以下のように説明されています。 3.コルーチンの概要 One can think of a coroutine as a light-weight thread. Like threads, coroutines can run in parallel, wait for each other and communicate. The biggest difference is that coroutines are very cheap, almost free: we can create thousands of them, and pay very little in terms of performance. True threads, on the other hand, are expensive to start and keep around. A thousand threads can be a serious challenge for a modern machine. 「Your first coroutine with Kotlin – Kotlin Programming Language (https://kotlinlang.org/docs/tutorials/coroutines/coroutines-basic-jvm.html )」より、記述の一 部を抜粋して引用
5.コルーチンの動作 fun main() = runBlocking<Unit> { val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } val two = async { doSomethingUsefulTwo() } println("The answer is ${one.await() + two.await()}") } println("Completed in $time ms") } suspend fun doSomethingUsefulOne(): Int { delay(1000L) // pretend we are doing something useful here return 13 } suspend fun doSomethingUsefulTwo(): Int { delay(1000L) // pretend we are doing something useful here, too return 29 }
5.コルーチンの動作 実行結果 The answer is 42 Completed in 1051 ms fun main() = runBlocking<Unit> { val time = measureTimeMillis { val one = async { doSomethingUsefulOne() } ← ❶ コルーチン起動 val two = async { doSomethingUsefulTwo() } ← ❶ コルーチン起動 println("The answer is ${one.await() + two.await()}") ← ❷ 2つのコ ルーチンの完了と戻り値を待ち、出力 } println("Completed in $time ms") }