一、介紹
1、CAS (Compare-And-Swap) 是一種硬件對併發的支持,針對多處理器 操作而設計的處理器中的一種特殊指令,用於管理對共享數據的並 發訪問。
2、CAS 是一種無鎖的非阻塞算法的實現。
3、CAS 包含了 3 個操作數
- 需要讀寫的內存值 V
- 進行比較的值 A
- 寫入的新值 B
當且僅當 V 的值等於 A 時,CAS 通過原子方式用新值 B 來更新 V 的 值,否則不會執行任何操作
二、代碼模擬
package com.example.juc;
import lombok.extern.slf4j.Slf4j;
/**
* @author haoxiansheng
* 模擬CAS 算法
*/
@Slf4j
public class CompareAndSwapTest {
public static void main(String[] args) {
CompareAndSwap compareAndSwap = new CompareAndSwap();
for (int i = 0; i < 100; i++) {
new Thread(() -> {
int expectValue = compareAndSwap.getVlaue();
int update = (int)Math.random() * 100;
boolean success = compareAndSwap.compareAndSet(expectValue, update);
log.info("success=>{},update=>{}", success, update);
}).start();
}
}
}
class CompareAndSwap {
private int vlaue;
// 獲取內存值
public synchronized int getVlaue() {
return vlaue;
}
// 比較
public synchronized int compareAndSwap(int expect, int update) {
int oldValue = vlaue;
if (oldValue == expect) {
this.vlaue = update;
}
return oldValue;
}
// 設置
public synchronized boolean compareAndSet(int expect, int update) {
return expect == compareAndSwap(expect, update);
}
}