java模拟CAS操作

2019-11-13  本文已影响0人  xin激流勇进
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;
    }
}

上一篇下一篇

猜你喜欢

热点阅读