public class SupkingxLock {
private static final Unsafe unsafe;
private static final long valueOffset;
private volatile int value = 0;
static {
try {
Class<Unsafe> unsafeClass = Unsafe.class;
Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
unsafe = (Unsafe) theUnsafe.get(null);
valueOffset = unsafe.objectFieldOffset
(SupkingxLock.class.getDeclaredField("value"));
} catch (Exception ex) {
throw new Error(ex);
}
}
public void lock() {
// 自旋
for (; ; ) {
// this 当前对象本身,valueOffset 位移偏移量,0:内存中的真值,1:将要变成的值
if (unsafe.compareAndSwapInt(this, valueOffset, 0, 1)) {
return;
}
// 如果不是自己想要的值,则将当前线程让出去
Thread.yield();
}
}
public void unlock() {
value = 0;
}
public static void main(String[] args) {
System.out.println(unsafe);
}
}