1. public class SupkingxLock {
    2. private static final Unsafe unsafe;
    3. private static final long valueOffset;
    4. private volatile int value = 0;
    5. static {
    6. try {
    7. Class<Unsafe> unsafeClass = Unsafe.class;
    8. Field theUnsafe = unsafeClass.getDeclaredField("theUnsafe");
    9. theUnsafe.setAccessible(true);
    10. unsafe = (Unsafe) theUnsafe.get(null);
    11. valueOffset = unsafe.objectFieldOffset
    12. (SupkingxLock.class.getDeclaredField("value"));
    13. } catch (Exception ex) {
    14. throw new Error(ex);
    15. }
    16. }
    17. public void lock() {
    18. // 自旋
    19. for (; ; ) {
    20. // this 当前对象本身,valueOffset 位移偏移量,0:内存中的真值,1:将要变成的值
    21. if (unsafe.compareAndSwapInt(this, valueOffset, 0, 1)) {
    22. return;
    23. }
    24. // 如果不是自己想要的值,则将当前线程让出去
    25. Thread.yield();
    26. }
    27. }
    28. public void unlock() {
    29. value = 0;
    30. }
    31. public static void main(String[] args) {
    32. System.out.println(unsafe);
    33. }
    34. }