我们这里自己手写了一个自旋锁,就是根据AtomicReference类,比较更新的特性,
    加锁:先看atomicReference 是不是 没有值,如果没有就加锁成功,锁为当前线程,如果有,就一直循环。
    解锁:就是将atomicReference的值设置为null

    自定义一个自旋锁

    1. import java.util.concurrent.atomic.AtomicReference;
    2. /**
    3. * 自旋锁
    4. */
    5. public class SpinlockDemo {
    6. // int 0
    7. // Thread null
    8. AtomicReference<Thread> atomicReference = new AtomicReference<>();
    9. // 加锁
    10. public void myLock(){
    11. Thread thread = Thread.currentThread();
    12. System.out.println(Thread.currentThread().getName() + "==> mylock");
    13. // 自旋锁
    14. while (!atomicReference.compareAndSet(null,thread)){
    15. }
    16. }
    17. // 解锁
    18. public void myUnLock(){
    19. Thread thread = Thread.currentThread();
    20. System.out.println(Thread.currentThread().getName() + "==> myUnlock");
    21. atomicReference.compareAndSet(thread,null);
    22. }
    23. }

    测试自旋

    1. import java.util.concurrent.TimeUnit;
    2. import java.util.concurrent.locks.ReentrantLock;
    3. public class TestSpinLock {
    4. public static void main(String[] args) throws InterruptedException {
    5. // ReentrantLock reentrantLock = new ReentrantLock();
    6. // reentrantLock.lock();
    7. // reentrantLock.unlock();
    8. // 底层使用的自旋锁CAS
    9. SpinlockDemo lock = new SpinlockDemo();
    10. new Thread(()-> {
    11. lock.myLock();
    12. try {
    13. TimeUnit.SECONDS.sleep(5);
    14. } catch (Exception e) {
    15. e.printStackTrace();
    16. } finally {
    17. lock.myUnLock();
    18. }
    19. },"T1").start();
    20. TimeUnit.SECONDS.sleep(1);
    21. new Thread(()-> {
    22. lock.myLock();
    23. try {
    24. TimeUnit.SECONDS.sleep(1);
    25. } catch (Exception e) {
    26. e.printStackTrace();
    27. } finally {
    28. lock.myUnLock();
    29. }
    30. },"T2").start();
    31. }
    32. }