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

61 lines
2.1 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
[AtomicBoolean  |  Android Developers](https://developer.android.com/reference/java/util/concurrent/atomic/AtomicBoolean)
## 初始化
```kotlin
val init = AtomicBoolean(false)
or
val inti = AtomicBoolean() // Default false
```
## read/write
`get()`取值,用`set()`設值
例:
```kotlin
if (init.get()) { ... } // 如果 init 是 true 的話
init.set(true) // 將 init 設為 true
```
## 其他function
### compareAndExchange
- [compareAndExchange](https://developer.android.com/reference/java/util/concurrent/atomic/AtomicBoolean#compareAndExchange(boolean,%20boolean))
```java
public final boolean compareAndExchange (
boolean expectedValue,
boolean newValue)
```
如果目前的值跟`expectedValue`相等,回傳目前值,並將目前值設為`newValue`
如果目前的值跟`expectedValue`不相等,回傳目前值,不做任何設定。
### compareAndSet
- [compareAndSet](https://developer.android.com/reference/java/util/concurrent/atomic/AtomicBoolean#compareAndSet(boolean,%20boolean))
```java
public final boolean compareAndSet (
boolean expectedValue,
boolean newValue)
```
如果目前的值跟`expectedValue`相等return `true`,並將目前值設為`newValue`
如果目前的值跟`expectedValue`不相等return `false`
## 用途
一般而言,`set``get` 已經夠用,但如果需要讀值並設定一個新值的話,那就需要 `compareAndSet` 或是 `compareAndExchange`,不然就需要另一個 `mutex` 來達到同樣效果。
假設一個情況,假設目前是 `false` 的情況下,我們可以存取某些資源,所以也要把值設為 `true`,用 `mutex` 的作法如下:
```kotlin
mutex.lock()
if (useable.get()) {
useable.set(false)
// Do something
} else {
...
}
mutex.unlock()
```
改用 `compareAndSet` 就是:
```kotlin
if (useable.compareAndSet(false, true)) {
// Do something
}
```
## 資料
- [java - compareandexchange() vs compareandset() of Atomic-Integer - Stack Overflow](https://stackoverflow.com/questions/60648557/compareandexchange-vs-compareandset-of-atomic-integer)