首页 > 代码库 > 通过CAS避免加锁

通过CAS避免加锁

package com.guo.day05;import java.util.concurrent.atomic.AtomicInteger;/** * Created by guo on 2017/6/3. */public class Seqience {    //    通过加锁防止互斥    private int value;    public synchronized int next1(){        return value++;    }    private AtomicInteger count =new AtomicInteger(0);    private int next2(){//        循环保证compareAndSet一直进行//        ABA问题的解决 添加了版本值        while(true){            int current = count.get();//读取内存中的值            int next = current+1;            //compareAndSet硬件指令一定是原子操作  比较内存的值和现在的值是否有变化            if(count.compareAndSet(current,next)){                return next;            }        }    }}

  

通过CAS避免加锁