• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

自旋锁

开发技术 开发技术 1周前 (05-05) 9次浏览

自旋锁

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

程序员灯塔
转载请注明原文链接:自旋锁
喜欢 (0)