并发编程(三)__模拟CAS算法
1 /* 2 * 模拟 CAS 算法 3 */ 4 public class TestCompareAndSwap { 5 6 public static void main(String[] args) { 7 final CompareAndSwap cas = new CompareAndSwap(); 8 9 for (int i = 0; i < 10; i++) { 10 new Thread(new Runnable() { 11 12 @Override 13 public void run() { 14 int expectedValue = cas.get(); 15 boolean b = cas.compareAndSet(expectedValue, (int)(Math.random() * 101)); 16 System.out.println(b); 17 } 18 }).start(); 19 } 20 21 } 22 23 } 24 25 class CompareAndSwap{ 26 private int value; 27 28 //获取内存值 29 public synchronized int get(){ 30 return value; 31 } 32 33 //比较 34 public synchronized int compareAndSwap(int expectedValue, int newValue){ 35 int oldValue = value; 36 37 if(oldValue == expectedValue){ 38 this.value = newValue; 39 } 40 41 return oldValue; 42 } 43 44 //设置 45 public synchronized boolean compareAndSet(int expectedValue, int newValue){ 46 return expectedValue == compareAndSwap(expectedValue, newValue); 47 } 48 }
纸上学来终觉浅,觉知此事需躬行