自旋锁

自旋锁

  • spinlock
    自定义一个锁测试

  • public class SpinLockDemo {
        AtomicReference<Thread> atomicReference = new AtomicReference();
    
        //加锁
        public void myLock() {
            Thread thread = Thread.currentThread();
            System.out.println(Thread.currentThread().getName() + "MyLock");
            //自旋锁
            while (!atomicReference.compareAndSet(null, thread)) {
    
            }
        }
    
        // 解锁
        public void myUnLock() {
            Thread thread = Thread.currentThread();
            System.out.println(Thread.currentThread().getName() + "myUnLock");
            atomicReference.compareAndSet(thread, null);
        }
    }
    
  • 在这里插入图片描述
  • public class Test01 {
        public static void main(String[] args) throws InterruptedException {
            /*ReentrantLock reentrantLock = new ReentrantLock();
            reentrantLock.lock();
            reentrantLock.unlock();*/
            // 底层使用的自旋锁CAS
            SpinLockDemo lock = new SpinLockDemo();
            new Thread(() -> {
                lock.myLock();
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.myUnLock();
                }
            }, "T1").start();
            TimeUnit.SECONDS.sleep(1);
            new Thread(() -> {
                lock.myLock();
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.myUnLock();
                }
            }, "T2").start();
        }
    }
    
posted @ 2021-05-05 14:11  saxon宋  阅读(54)  评论(0)    收藏  举报