利用CAS構造一個TryLock自定義顯式鎖

CAS的全稱是Compare And Swap 即比較交換

CAS的博文

TryLock實現(xiàn)類CompareAndSetLock.java

public class CompareAndSetLock {

    private AtomicInteger value = new AtomicInteger(0);
    private Thread threadLocal;

    /**
     * <p>get lock</p>
     */
    public void tryLock() throws GetTryLockException {
        boolean success = value.compareAndSet(0, 1);
        if(!success){
            throw new GetTryLockException("get lock fail");
        }
        this.threadLocal = Thread.currentThread();
    }

    /**
     * <p>unlock</p>
     */
    public void unlock(){
        if(value.get() == 0){
            return;
        }
        if(threadLocal == Thread.currentThread())
            value.compareAndSet(1,0);
    }

}

TryLock 測試類 TryLockTest.java

public class TryLockTest {
    private static CompareAndSetLock lock = new CompareAndSetLock();

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(){
                @Override
                public void run() {
                    try {
                        doSomething();
                    } catch (GetTryLockException e) {
                        //e.printStackTrace();
                        System.out.println("get lock fail >>> do other thing.");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

    private static void doSomething() throws GetTryLockException, InterruptedException {
        try {
            lock.tryLock();
            System.out.println(Thread.currentThread().getName()+" get lock success.");
            Thread.sleep(100_0000);
        }finally {
            lock.unlock();
        }
    }
}

獲取鎖自定義異常類GetTryLockException.java

public class GetTryLockException extends Exception {
  public GetTryLockException() {
      super();
  }
  public GetTryLockException(String message) {
      super(message);
  }
}

運行結果

Thread-0 get lock success.
get lock fail >>> do other thing.
get lock fail >>> do other thing.
get lock fail >>> do other thing.
get lock fail >>> do other thing.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容