public class SpinLock {
private volatile int lock = 0;
private static Unsafe theUnsafe;
private static long lockOff;
static {
try {
Field theUnsafeField = Unsafe.class.getDeclaredField(“theUnsafe”);
theUnsafeField.setAccessible(true);
theUnsafe = (Unsafe) theUnsafeField.get(null);
Field lockField = SpinLock.class.getDeclaredField(“lock”);
lockOff = theUnsafe.objectFieldOffset(lockField);
} catch (Exception e) {
e.printStackTrace();
}
}
public void lock() {
while (! theUnsafe.compareAndSwapInt(this, lockOff, 0, 1)){
}
}
public void unlock() {
theUnsafe.compareAndSwapInt(this, lockOff, 1, 0);
}
}
我也写了个自旋锁,