获取Unsafe对象
CAS上锁解锁
volatite int status = 0;
// 魔法类
private static Unsafe unsafe = null;
// 某一个属性值得偏移量
private static long stateOffset;
// 获取Unsafe对象 复制粘贴即用
static {
Field singlenoneInstanceField = null;
try{
singlenoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
singlenoneInstanceField.setAccessible(true);
unsafe = (Unsafe)singlenoneInstanceField.get(null);
// 当前的"status"为获取status属性的内存偏移量
stateOffset= unsafe.objectFieldOffset(当前类.class.getDeclaredField("status"));
}catch(Exception e){
e.printStackTrace();
}
}
void lock(){
// cas
whlie(!compareAndSet(0,1)){
// 系统调用
}
}
Booblean compareAndSet(int oldVal, int newVal){
return unsafe.compareAndSwapInt(this,stateOffset,0,1);
}
void unlock(){
status = 0;
}
compareAndSwapInt(Object,offset(偏移量),期待值,交换值)
方法详解:
①先比较:将当前Object中内存偏移量为offset的值与期待值相比
②如果相同则执行③,如果不相同执行④
③后交换:将交换值赋给偏移量为offset,返回true
④返回false
临界区是指lock()与unlock()之间的代码。