Java多線程⑥----Lock知識點梳理

多線程文章目錄

激烈競爭lock比synchonized更佳

lock、condition、ReadWriteLock 三個接口

Lock

可以看到lock更加靈活;注意需要在finally方法釋放鎖

 

下面對上述的5個方法進行一句話總結:
lock():獲取鎖,不可中斷、不可超時。
lockInterruptibly():獲取鎖,可以中斷、不可超時。
trylock():獲取當前可用的鎖並返回true,否則返回false,無需中斷、無需超時。
tryLock(long time, TimeUnit unit):獲取限定時間可用的鎖並返回true,否則返回false,可以中斷、可以超時。
unlock():解鎖。

Condition

Condition可以替代傳統的線程間通信,用await()替代wait,用signal替代notify(),用signalAll()替代notifyAll()。
因爲Object下面的wait/notify/notifyAll方法都是final的,所以名稱上全都發生了改變。傳統線程通信方式,condition都能實現。
condition()是被綁定到Lock上面的,要創建一個Lock的conditon,需要用newCondition
ArrayBlockingQueue 使用condition實現

因爲有時候獲得鎖的線程發現其某個條件不滿足導致不能繼續後面的業務邏輯,此時該線程只能先釋放鎖,等待條件滿足。

參考代碼是網上找的

public class LockDemo {
    final Lock lock = new ReentrantLock();
    final Condition notFull  = lock.newCondition();
    final Condition notEmpty = lock.newCondition();

    final Object[] items = new Object[100];
    int putptr, takeptr, count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length)
                notFull.await();
            items[putptr] = x;
            if (++putptr == items.length) putptr = 0;
            ++count;
            notEmpty.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        try {
            while (count == 0)
                notEmpty.await();
            Object x = items[takeptr];
            if (++takeptr == items.length) takeptr = 0;
            --count;
            notFull.signalAll();
            return x;
        } finally {
            lock.unlock();
        }
    }
}

應用:

ReentrantLock 可重入鎖,(公平鎖加參數,ArrayBlockingQueue開啓公平鎖)

ReadWriterLock 讀寫鎖 支持併發讀 只要沒有線程進行寫操作,多個線程可以同時持有這個只讀鎖

https://blog.csdn.net/hanchao5272/article/details/79683202 可重入鎖介紹

lock和 synchonized應用簡單比較

https://blog.csdn.net/hanchao5272/article/details/79679919

 

原理:

Lock實現過程中的幾個關鍵詞:計數值、雙向鏈表、CAS+自旋、代碼LockSupport.park

https://juejin.im/entry/5b9f0571f265da0a8f35b4bb

Linux 下的 POSIX thread 是輕量級的 Mutex.

底層Posix的 加鎖pthread_mutex_lock()、解鎖pthread_mutex_unlock()和

嘗試加鎖 pthread_mutex_trylock() 、互斥量 ---信號量

 

Lock的底層實現也是Posix lock mutex,但是通過 CAS和 ASQ(AbstractQueuedSynchronizer)隊列;

來使得這個過程更高效和靈活.

 

LockSupport.park 是什麼

https://blog.csdn.net/hengyunabc/article/details/28126139

https://www.jianshu.com/p/f32f941335aa

 

淺談mutex

http://dreamrunner.org/blog/2014/06/29/qian-tan-mutex-lock/

 

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