0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Kotlin: Coroutine の使い方

Last updated at Posted at 2023-10-23

プログラム

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

play.kotinlang.org で実行した時の様子
image.png

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
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?