自旋鎖的實現

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、分析

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章