手寫自旋鎖

手寫自旋鎖

/**
 * 手寫了一個自旋鎖,直接調用spinLock()、unSpinLock()即可完成多線程加鎖的控制
 * 代碼中使用了原子引用類,原子引用類的底層原理就是CAS,CAS思想就是自旋,我們這裏借用了這個思想,使用while循環完成自旋
 */
public class SpinLockTest {

    //定義原子引用類,保證原子性,volatile保證可見性、有序性
    private volatile AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void spinLock(){
        Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(null, thread)){}
        System.out.println(thread.getName() + "已經獲取鎖");
    }

    public void unSpinLock(){
        Thread thread = Thread.currentThread();
        while (!atomicReference.compareAndSet(thread, null)){}
        System.out.println(thread.getName() + "已經釋放鎖");
    }

    public static void main(String[] args) {
        SpinLockTest spinLockTest = new SpinLockTest();

        new Thread(new Runnable() {
            @Override
            public void run() {
                spinLockTest.spinLock();
                System.out.println("thread1 在執行");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println();
                spinLockTest.unSpinLock();
            }
        }, "thread1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                spinLockTest.spinLock();
                System.out.println("thread2 在執行");
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println();
                spinLockTest.unSpinLock();
            }
        }, "thread2").start();
    }

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