美文网首页
java模拟CAS操作

java模拟CAS操作

作者: xin激流勇进 | 来源:发表于2019-11-13 16:53 被阅读0次
    import java.util.concurrent.atomic.AtomicInteger;
    
    /**
     * 使用java模拟jvm中的cas
     * @author torrent
     * @date 19-11-13 下午4:16
     */
    public class CAS {
        private static int i = 0;
    
        private static AtomicInteger integer = new AtomicInteger(0);
    
        private static MyAtomicInteger myAtomicInteger = new MyAtomicInteger(0);
    
        public static void incr() {
            i ++;
        }
    
        public static int getI() {
            return i;
        }
    
        public static void main(String[] args) {
    //        for (int i = 0; i < 100; i++) {
    //            new Thread(CAS::incr).start();
    //        }
    
    //        for (int j = 0; j < 100; j++) {
    //            new Thread(() -> {
    //                int i = integer.incrementAndGet();
    //            }).start();
    //        }
    
            for (int j = 0; j < 100; j++) {
                new Thread(() -> {
                    int i = myAtomicInteger.incrementAndGet();
                    System.out.println(i);
                }).start();
            }
    
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    //        System.out.println(getI());
    //        System.out.println(integer.get());
            System.out.println(myAtomicInteger.getValue());
        }
    }
    
    class MyAtomicInteger {
    
        public MyAtomicInteger(int value) {
            this.value = value;
        }
    
        //加不加volatile打印结果不同
        private volatile int value; //内存中的值
    
        public synchronized int getValue() {
            return value;
        }
    
        private synchronized int compareAndSwap(int exceptedValue, int newValue) {
            int oldValue = value;
    
            if (exceptedValue == oldValue) {
                value = newValue;
            }
    
            return oldValue;
        }
    
        private synchronized boolean compareAndSet(int exceptedValue, int newValue) {
            return exceptedValue == compareAndSwap(exceptedValue, newValue);
        }
    
        synchronized int incrementAndGet() {
    
            boolean isSuccess;
    
            do {
                isSuccess = compareAndSet(value, value + 1);
            } while (!isSuccess);
    
            return value;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:java模拟CAS操作

          本文链接:https://www.haomeiwen.com/subject/exhkictx.html