public class MyCAS { private volatile Integer value; //volatile 保证内存可见 get()到内存中的最新值 public MyCAS() { } public MyCAS(Integer initialValue) { this.value = initialValue; } final Integer get(){ return value; } public final void set(int newValue) { this.value = newValue; } public synchronized void compareAndSwap(int expectedValue){ int current = get(); //内存值 if (current==expectedValue){ //预期值等于内存值 赋新值 // System.out.println(Thread.currentThread().getName()+"加一成功"); set(current+1); }else { // System.out.println(Thread.currentThread().getName()+"加一失败"); this.addAndGet(get()); //递归 直到当前线程执行成功 } } //expectedValue 预期值 public void addAndGet(Integer expectedValue ){ compareAndSwap(expectedValue); } }
; public class TestMyCas { static MyCAS myCAS = new MyCAS(0); public static class MyThread implements Runnable{ @Override public void run() { for (int i=0;i<100000;i++){ // System.out.println(myCAS.get()); myCAS.addAndGet(myCAS.get()); } } } public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); Thread t1 = new Thread(myThread); Thread t2 = new Thread(myThread); t1.start(); t2.start(); Thread.sleep(1000); System.out.println(myCAS.get()); } }