自旋锁的实现

1、请自己写一个自旋锁。

OK,不仅写好了;而且验证一遍。

/**
 * @program: mybatis
 * @description: 自己实现一个自旋锁
 * @author: Miller.FAN
 * @create: 2019-11-13 14:19
 **/
public class MyLock {

    private AtomicReference atomicReference = new AtomicReference();


        public void getLock() {
            Thread thread = Thread.currentThread();
            System.out.printf(thread.getName() + "\t come in \n");
            while(!atomicReference.compareAndSet(null,thread))
            {
               // System.out.println("里面的哥们儿快点,我憋不住了!");
            }
        }

        public void giveLock() {
            Thread thread = Thread.currentThread();
            System.out.printf(thread.getName() + "\t back out \n");
            atomicReference.compareAndSet(thread,null);
            System.out.println(thread.getName() + "完事了,马上出来!\n");
        }



    public static void main(String[] args) {
        MyLock m_lock = new MyLock();
        new Thread(()-> {
            m_lock.getLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                m_lock.giveLock();
            }
        },"AA").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()-> {
            m_lock.getLock();
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                m_lock.giveLock();
            }
        },"BB").start();

    }
}

2、测试结果

AA	 come in 
BB	 come in 
AA	 back out 
AA完事了,马上出来!

BB	 back out 
BB完事了,马上出来!

3、分析

发布了85 篇原创文章 · 获赞 21 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41670928/article/details/103048895
今日推荐