[Android] 016. Thread / Timer

Coroutineは別途確認です

Executorなどここで説明されて無いものは以下を参照
https://developer.android.com/guide/background/threading?hl=ja

Thread

java.lang.Threadも使えますがkotlin.concurrent.threadを使用します

thread

なお一度実行したthreadの再利用(thread_の使いまわし)はできません

// start()不要で実行される
thread {...}

// start = falseにすることで開始タイミングを変更できる
val thread_ = thread(start = false) {...}
thread_.start()

// 処理終了待ち
thread_.join()
// start = falseを使用しない場合は以下のようにもできます
thread {...}.join()

UIスレッドでの処理

// UIスレッドでの処理
runOnUiThread {...}

排他制御

synchronizedもしくはメソッドに@Synchronizedをつける

val lock = Object()
fun test(text: String) {
    synchronized(lock) {
        repeat(10) {
            println("$text:$it")
            Thread.sleep(10)
        }
    }
}

thread { test("1") }
thread { test("2") }
@Synchronized
fun test(text: String) {...}

Timer

タイマーはkotlinでもjava.lang.Timerを使用します

val timer = Timer().schedule(0, 100) {...}
// キャンセル
timer.cancel()
// またはタイマー処理内でキャンセル
Timer().schedule(0, 100) { cancel() }

Android Studio Dolphin 2021.3.1 Patch 1 built on September 30, 2022