Files
Obsidian-Main/-20.01. Programming/Kotlin/AtomicBoolean.md

2.1 KiB
Raw Blame History

AtomicBoolean  |  Android Developers

初始化

val init = AtomicBoolean(false)
or
val inti = AtomicBoolean() // Default false

read/write

get()取值,用set()設值 例:

if (init.get()) { ... } // 如果 init 是 true 的話

init.set(true) // 將 init 設為 true

其他function

compareAndExchange

public final boolean compareAndExchange (
    boolean expectedValue, 
    boolean newValue)

如果目前的值跟expectedValue相等,回傳目前值,並將目前值設為newValue。 如果目前的值跟expectedValue不相等,回傳目前值,不做任何設定。

compareAndSet

public final boolean compareAndSet (
    boolean expectedValue, 
    boolean newValue)

如果目前的值跟expectedValue相等return true,並將目前值設為newValue。 如果目前的值跟expectedValue不相等return false

用途

一般而言,setget 已經夠用,但如果需要讀值並設定一個新值的話,那就需要 compareAndSet 或是 compareAndExchange,不然就需要另一個 mutex 來達到同樣效果。 假設一個情況,假設目前是 false 的情況下,我們可以存取某些資源,所以也要把值設為 true,用 mutex 的作法如下:

mutex.lock()
if (useable.get()) {
    useable.set(false)
    // Do something
} else {
    ...
}
mutex.unlock()

改用 compareAndSet 就是:

if (useable.compareAndSet(false, true)) {
    // Do something
}

資料