首页 > 其他 > 详细

自旋锁

时间:2021-05-05 17:26:37      阅读:23      评论:0      收藏:0      [点我收藏+]

自旋锁

  • 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();
        }
    }
    

自旋锁

原文:https://www.cnblogs.com/saxonsong/p/14731640.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!