1、getAndIncrement 方法
底层使用了unsafe.getAndAddInt(object,offset,deta)
int getAndAddInt(Object,offset,int deta){
int v ;
do{
v = unsafe.getIntVolatile(object,offset);
}while(!unsafe.compareAndSet(object,offset,v,v+1))
return v;
}
2、incrementAndGet()方法
同样使用了unsafe类的getAndInt()
与getAndIncrement()一样,只不过在返回值+1;
3、compareAndSet方法
底层使用unsafe类的compareAndSet(obj,offset,expect,update); 返回类型是布尔值
补充unsafe类只能由Boot classLoader 加载
所以如果非jdk类库使用 初始化应该利用反射
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
Unsafe unsafe = (Unsafe) theUnsafe.get(null);