Java中的顯示鎖ReentrantLock使用與原理詳解
考慮一個場景,輪流打印0-100以內(nèi)的技術(shù)和偶數(shù)。通過使用 synchronize 的 wait,notify機制就可以實現(xiàn),核心思路如下:
使用兩個線程,一個打印奇數(shù),一個打印偶數(shù)。這兩個線程會共享一個數(shù)據(jù),數(shù)據(jù)每次自增,當打印奇數(shù)的線程發(fā)現(xiàn)當前要打印的數(shù)字不是奇數(shù)時,執(zhí)行等待,否則打印奇數(shù),并將數(shù)字自增1,對于打印偶數(shù)的線程也是如此
//打印奇數(shù)的線程 private static class OldRunner implements Runnable{ private MyNumber n; public OldRunner(MyNumber n) { this.n = n; } public void run() { while (true){ n.waitToOld(); //等待數(shù)據(jù)變成奇數(shù) System.out.println("old:" + n.getVal()); n.increase(); if (n.getVal()>98){ break; } } } } //打印偶數(shù)的線程 private static class EvenRunner implements Runnable{ private MyNumber n; public EvenRunner(MyNumber n) { this.n = n; } public void run() { while (true){ n.waitToEven(); //等待數(shù)據(jù)變成偶數(shù) System.out.println("even:"+n.getVal()); n.increase(); if (n.getVal()>99){ break; } } } }
共享的數(shù)據(jù)如下
private static class MyNumber{ private int val; public MyNumber(int val) { this.val = val; } public int getVal() { return val; } public synchronized void increase(){ val++; notify(); //數(shù)據(jù)變了,喚醒另外的線程 } public synchronized void waitToOld(){ while ((val % 2)==0){ try { System.out.println("i am "+Thread.currentThread().getName()+" ,but now is even:"+val+",so wait"); wait(); //只要是偶數(shù),一直等待 } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void waitToEven(){ while ((val % 2)!=0){ try { System.out.println("i am "+Thread.currentThread().getName()+" ,but now old:"+val+",so wait"); wait(); //只要是奇數(shù),一直等待 } catch (InterruptedException e) { e.printStackTrace(); } } } }
運行代碼如下
MyNumber n = new MyNumber(0); Thread old=new Thread(new OldRunner(n),"old-thread"); Thread even = new Thread(new EvenRunner(n),"even-thread"); old.start(); even.start();
運行結(jié)果如下
i am old-thread ,but now is even:0,so wait
even:0
i am even-thread ,but now old:1,so wait
old:1
i am old-thread ,but now is even:2,so wait
even:2
i am even-thread ,but now old:3,so wait
old:3
i am old-thread ,but now is even:4,so wait
even:4
i am even-thread ,but now old:5,so wait
old:5
i am old-thread ,but now is even:6,so wait
even:6
i am even-thread ,but now old:7,so wait
old:7
i am old-thread ,but now is even:8,so wait
even:8
上述方法使用的是 synchronize的 wait notify機制,同樣可以使用顯示鎖來實現(xiàn),兩個打印的線程還是同一個線程,只是使用的是顯示鎖來控制等待事件
private static class MyNumber{ private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); private int val; public MyNumber(int val) { this.val = val; } public int getVal() { return val; } public void increase(){ lock.lock(); try { val++; condition.signalAll(); //通知線程 }finally { lock.unlock(); } } public void waitToOld(){ lock.lock(); try{ while ((val % 2)==0){ try { System.out.println("i am should print old ,but now is even:"+val+",so wait"); condition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } }finally { lock.unlock(); } } public void waitToEven(){ lock.lock(); //顯示的鎖定 try{ while ((val % 2)!=0){ try { System.out.println("i am should print even ,but now old:"+val+",so wait"); condition.await();//執(zhí)行等待 } catch (InterruptedException e) { e.printStackTrace(); } } }finally { lock.unlock(); //顯示的釋放 } } }
同樣可以得到上述的效果
顯示鎖的功能
顯示鎖在java中通過接口Lock提供如下功能
lock: 線程無法獲取鎖會進入休眠狀態(tài),直到獲取成功
- lockInterruptibly: 如果獲取成功,立即返回,否則一直休眠到線程被中斷或者是獲取成功
- tryLock:不會造成線程休眠,方法執(zhí)行會立即返回,獲取到了鎖,返回true,否則返回false
- tryLock(long time, TimeUnit unit) throws InterruptedException : 在等待時間內(nèi)沒有發(fā)生過中斷,并且沒有獲取鎖,就一直等待,當獲取到了,或者是線程中斷了,或者是超時時間到了這三者發(fā)生一個就返回,并記錄是否有獲取到鎖
- unlock:釋放鎖
- newCondition:每次調(diào)用創(chuàng)建一個鎖的等待條件,也就是說一個鎖可以擁有多個條件
Condition的功能
接口Condition把Object的監(jiān)視器方法wait和notify分離出來,使得一個對象可以有多個等待的條件來執(zhí)行等待,配合Lock的newCondition來實現(xiàn)。
- await:使當前線程休眠,不可調(diào)度。這四種情況下會恢復 1:其它線程調(diào)用了signal,當前線程恰好被選中了恢復執(zhí)行;2: 其它線程調(diào)用了signalAll;3:其它線程中斷了當前線程 4:spurious wakeup (假醒)。無論什么情況,在await方法返回之前,當前線程必須重新獲取鎖
- awaitUninterruptibly:使當前線程休眠,不可調(diào)度。這三種情況下會恢復 1:其它線程調(diào)用了signal,當前線程恰好被選中了恢復執(zhí)行;2: 其它線程調(diào)用了signalAll;3:spurious wakeup (假醒)。
- awaitNanos:使當前線程休眠,不可調(diào)度。這四種情況下會恢復 1:其它線程調(diào)用了signal,當前線程恰好被選中了恢復執(zhí)行;2: 其它線程調(diào)用了signalAll;3:其它線程中斷了當前線程 4:spurious wakeup (假醒)。5:超時了
- await(long time, TimeUnit unit) :與awaitNanos類似,只是換了個時間單位
- awaitUntil(Date deadline):與awaitNanos相似,只是指定日期之后返回,而不是指定的一段時間
- signal:喚醒一個等待的線程
- signalAll:喚醒所有等待的線程
ReentrantLock
從源碼中可以看到,ReentrantLock的所有實現(xiàn)全都依賴于內(nèi)部類Sync和ConditionObject。
Sync本身是個抽象類,負責手動lock和unlock,ConditionObject則實現(xiàn)在父類AbstractOwnableSynchronizer中,負責await與signal
Sync的繼承結(jié)構(gòu)如下
Sync的兩個實現(xiàn)類,公平鎖和非公平鎖
公平的鎖會把權(quán)限給等待時間最長的線程來執(zhí)行,非公平則獲取執(zhí)行權(quán)限的線程與線程本身的等待時間無關(guān)
默認初始化ReentrantLock使用的是非公平鎖,當然可以通過指定參數(shù)來使用公平鎖
public ReentrantLock() { sync = new NonfairSync(); }
當執(zhí)行獲取鎖時,實際就是去執(zhí)行 Sync 的lock操作:
public void lock() { sync.lock(); }
對應在不同的鎖機制中有不同的實現(xiàn)
1、公平鎖實現(xiàn)
final void lock() { acquire(1); }
2、非公平鎖實現(xiàn)
final void lock() { if (compareAndSetState(0, 1)) //先看當前鎖是不是已經(jīng)被占有了,如果沒有,就直接將當前線程設(shè)置為占有的線程 setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); //鎖已經(jīng)被占有的情況下,嘗試獲取 }
二者都調(diào)用父類AbstractQueuedSynchronizer的方法
public final void acquire(int arg) { if (!tryAcquire(arg) && acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //一旦搶失敗,就會進入隊列,進入隊列后則是依據(jù)FIFO的原則來執(zhí)行喚醒 selfInterrupt(); }
當執(zhí)行unlock時,對應方法在父類AbstractQueuedSynchronizer中
public final boolean release(int arg) { if (tryRelease(arg)) { Node h = head; if (h != null && h.waitStatus != 0) unparkSuccessor(h); return true; } return false; }
公平鎖和非公平鎖則分別對獲取鎖的方式tryAcquire
做了實現(xiàn),而tryRelease的實現(xiàn)機制則都是一樣的
公平鎖實現(xiàn)tryAcquire
源碼如下
protected final boolean tryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); //獲取當前的同步狀態(tài) if (c == 0) { //等于0 表示沒有被其它線程獲取過鎖 if (!hasQueuedPredecessors() && compareAndSetState(0, acquires)) { //hasQueuedPredecessors 判斷在當前線程的前面是不是還有其它的線程,如果有,也就是鎖sync上有一個等待的線程,那么它不能獲取鎖,這意味著,只有等待時間最長的線程能夠獲取鎖,這就是是公平性的體現(xiàn) //compareAndSetState 看當前在內(nèi)存中存儲的值是不是真的是0,如果是0就設(shè)置成accquires的取值。對于JAVA,這種需要直接操作內(nèi)存的操作是通過unsafe來完成,具體的實現(xiàn)機制則依賴于操作系統(tǒng)。 //存儲獲取當前鎖的線程 setExclusiveOwnerThread(current); return true; } } else if (current == getExclusiveOwnerThread()) { //判斷是不是當前線程獲取的鎖 int nextc = c + acquires; if (nextc < 0)//一個線程能夠獲取同一個鎖的次數(shù)是有限制的,就是int的最大值 throw new Error("Maximum lock count exceeded"); setState(nextc); //在當前的基礎(chǔ)上再增加一次鎖被持有的次數(shù) return true; } //鎖被其它線程持有,獲取失敗 return false; }
非公平鎖實現(xiàn)tryAcquire
獲取的關(guān)鍵實現(xiàn)為nonfairTryAcquire
,源碼如下
final boolean nonfairTryAcquire(int acquires) { final Thread current = Thread.currentThread(); int c = getState(); if (c == 0) { //鎖沒有被持有 //可以看到這里會無視sync queue中是否有其它線程,只要執(zhí)行到了當前線程,就會去獲取鎖 if (compareAndSetState(0, acquires)) { setExclusiveOwnerThread(current); //在判斷一次是不是鎖沒有被占有,沒有就去標記當前線程擁有這個鎖了 return true; } } else if (current == getExclusiveOwnerThread()) { int nextc = c + acquires; if (nextc < 0) // overflow throw new Error("Maximum lock count exceeded"); setState(nextc);//如果當前線程已經(jīng)占有過,增加占有的次數(shù) return true; } return false; }
釋放鎖的機制
protected final boolean tryRelease(int releases) { int c = getState() - releases; if (Thread.currentThread() != getExclusiveOwnerThread()) //只能是線程擁有這釋放 throw new IllegalMonitorStateException(); boolean free = false; if (c == 0) { //當占有次數(shù)為0的時候,就認為所有的鎖都釋放完畢了 free = true; setExclusiveOwnerThread(null); } setState(c); //更新鎖的狀態(tài) return free; }
從源碼的實現(xiàn)可以看到
ReentrantLock獲取鎖時,在鎖已經(jīng)被占有的情況下,如果占有鎖的線程是當前線程,那么允許重入,即再次占有,如果由其它線程占有,則獲取失敗,由此可見,ReetrantLock本身對鎖的持有是可重入的,同時是線程獨占的
。
公平與非公平就體現(xiàn)在,當執(zhí)行的線程去獲取鎖的時候,公平的會去看是否有等待時間比它更長的,而非公平的就優(yōu)先直接去占有鎖
ReentrantLock的tryLock()與tryLock(long timeout, TimeUnit unit):
public boolean tryLock() { //本質(zhì)上就是執(zhí)行一次非公平的搶鎖 return sync.nonfairTryAcquire(1); }
有時限的tryLock核心代碼是 sync.tryAcquireNanos(1, unit.toNanos(timeout));
,由于有超時時間,它會直接放到等待隊列中,他與后面要講的AQS的lock原理中acquireQueued的區(qū)別在于park的時間是有限的,詳見源碼 AbstractQueuedSynchronizer.doAcquireNanos
為什么需要顯示鎖
內(nèi)置鎖功能上有一定的局限性,它無法響應中斷,不能設(shè)置等待的時間
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于Java中數(shù)組切片的幾種方法(獲取數(shù)組元素)
這篇文章主要介紹了關(guān)于Java中數(shù)組切片的幾種方法(獲取數(shù)組元素),切片是數(shù)組的一個引用,因此切片是引用類型,在進行傳遞時,遵守引用傳遞的機制,需要的朋友可以參考下2023-05-05Spring中BeanUtils.copyProperties的坑及解決
這篇文章主要介紹了Spring中BeanUtils.copyProperties的坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09解決Intellij IDEA運行報Command line is too long的問題
這篇文章主要介紹了解決Intellij IDEA運行報Command line is too long的問題,本文通過兩種方案給大家詳細介紹,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05Feign調(diào)用接口解決處理內(nèi)部異常的問題
這篇文章主要介紹了Feign調(diào)用接口解決處理內(nèi)部異常的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06Springboot整合Redis實現(xiàn)超賣問題還原和流程分析(分布式鎖)
最近在研究超賣的項目,寫一段簡單正常的超賣邏輯代碼,多個用戶同時操作同一段數(shù)據(jù)出現(xiàn)問題,糾結(jié)該如何處理呢?下面小編給大家?guī)砹薙pringboot整合Redis實現(xiàn)超賣問題還原和流程分析,感興趣的朋友一起看看吧2021-10-10mybatis動態(tài)sql之Map參數(shù)的講解
今天小編就為大家分享一篇關(guān)于mybatis動態(tài)sql之Map參數(shù)的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03詳解如何用spring Restdocs創(chuàng)建API文檔
這篇文章將帶你了解如何用spring官方推薦的restdoc去生成api文檔。具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05Spring boot攔截器實現(xiàn)IP黑名單的完整步驟
這篇文章主要給大家介紹了關(guān)于Spring boot攔截器實現(xiàn)IP黑名單的完整步驟,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Spring boot攔截器具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2020-06-06Springboot?JPA如何使用distinct返回對象
這篇文章主要介紹了Springboot?JPA如何使用distinct返回對象,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02