自旋锁

自旋锁

  • 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();
        }
    }
    
上一篇:Metasploit 笔记


下一篇:使用semaphore写一个显示锁