《利用CAS實現自旋鎖》

利用CAS實現自旋鎖

1.編寫自旋鎖

import java.util.concurrent.atomic.AtomicBoolean;
//自旋鎖
public class SpinLock {
    //CAS
    private AtomicBoolean cas = new AtomicBoolean(false);
    //鎖持有者線程
    private Thread spinLockOwnerThread = null;

    public void lock(){

        while (!cas.compareAndSet(false,true))
        {
            //CAS自旋
        }
        spinLockOwnerThread = Thread.currentThread();
    }

    public void unLock(){
        //當前線程等於鎖持有着線程才允許解鎖
        if (Thread.currentThread()==spinLockOwnerThread)
        {
            cas.set(false);
            spinLockOwnerThread = null;
        }
    }
}

2.測試自旋鎖

class Test {
    //引入自旋鎖
    private static final SpinLock spinLock = new SpinLock();

    public static void main(String[] args) {
        Thread t1  = new Thread(Test::run,"t1");
        Thread t2  = new Thread(Test::run,"t2");
        Thread t3  = new Thread(Test::run,"t3");
        Thread t4  = new Thread(Test::run,"t4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

    public static void run(){
        spinLock.lock();
        System.out.println(Thread.currentThread().getName());
        try 
        {
            Thread.sleep(5000);
        } 
        catch (InterruptedException e) 
        {
            e.printStackTrace();
        }
        finally
        {
          spinLock.unLock();
        }
      
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章