プログラム
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
suspend fun main() = coroutineScope {
val aa = 10
val bb = 20
var cc = 0
var dd = 0
launch {
delay(1000)
println("Kotlin Coroutines World!")
cc = aa + bb
dd = aa - bb
println("cc = $cc\t\tdd = $dd")
}
println("こんにちは")
println("cc = $cc\t\tdd = $dd")
}
実行結果
こんにちは
cc = 0 dd = 0
Kotlin Coroutines World!
cc = 30 dd = -10
Coroutine の終了を待機
.join を加えます。
プログラム
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
suspend fun main() = coroutineScope {
val aa = 10
val bb = 20
var cc = 0
var dd = 0
launch {
delay(1000)
println("Kotlin Coroutines World!")
cc = aa + bb
dd = aa - bb
println("cc = $cc\t\tdd = $dd")
}.join()
println("こんにちは")
println("cc = $cc\t\tdd = $dd")
}
実行結果
Kotlin Coroutines World!
cc = 30 dd = -10
こんにちは
cc = 30 dd = -10