模拟CAS
|Word count:258|Reading time:1min|Post View:
模拟CAS
CAS
CAS是一种无锁的非阻塞算法,全称为:Compare-and-swap(比较并交换)算法保证数据的原子性,CAS是硬件对于并发操作共享数据的支持,包含三个操作数,大致思路是:先比较目标对象现值是否和旧值一致,如果一致,则更新对象为新值;如果不一致,则表明对象已经被其他线程修改,直接返回.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
public class TestCompareAndSwap { public static void main(String[] args) { final CompareAndSwap compareAndSwap = new CompareAndSwap(); for(int i = 0;i < 10;i++){ new Thread(new Runnable() { @Override public void run() { int expectedValue = compareAndSwap.getValue(); boolean b = compareAndSwap.compareAndSet(expectedValue,(int)(Math.random()*101)); System.out.println(b); } }).start(); } } }
class CompareAndSwap{ private int value; public synchronized int getValue(){ return value; } public synchronized int compareAndSwap(int expectedValue, int newValue){ int oldValue = value; if (oldValue == expectedValue){ this.value = newValue; } return oldValue; } public synchronized boolean compareAndSet(int expectedValue, int newValue){ return expectedValue == compareAndSwap(expectedValue,newValue); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| true false true false false false true true true true
Process finished with exit code 0
|