考慮一個場景,輪流打印0-100以內(nèi)的技術(shù)和偶數(shù)。通過使用 synchronize 的 wait,notify機(jī)制就可以實現(xiàn),核心思路如下:
使用兩個線程,一個打印奇數(shù),一個打印偶數(shù)。這兩個線程會共享一個數(shù)據(jù),數(shù)據(jù)每次自增,當(dāng)打印奇數(shù)的線程發(fā)現(xiàn)當(dāng)前要打印的數(shù)字不是奇數(shù)時,執(zhí)行等待,否則打印奇數(shù),并將數(shù)字自增1,對于打印偶數(shù)的線程也是如此
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//打印奇數(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ù)如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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(); } } } } |
運行代碼如下
1
2
3
4
5
|
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機(jī)制,同樣可以使用顯示鎖來實現(xiàn),兩個打印的線程還是同一個線程,只是使用的是顯示鎖來控制等待事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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: 線程無法獲取鎖會進(jìn)入休眠狀態(tài),直到獲取成功
- lockinterruptibly: 如果獲取成功,立即返回,否則一直休眠到線程被中斷或者是獲取成功
- trylock:不會造成線程休眠,方法執(zhí)行會立即返回,獲取到了鎖,返回true,否則返回false
- trylock(long time, timeunit unit) throws interruptedexception : 在等待時間內(nèi)沒有發(fā)生過中斷,并且沒有獲取鎖,就一直等待,當(dāng)獲取到了,或者是線程中斷了,或者是超時時間到了這三者發(fā)生一個就返回,并記錄是否有獲取到鎖
- unlock:釋放鎖
- newcondition:每次調(diào)用創(chuàng)建一個鎖的等待條件,也就是說一個鎖可以擁有多個條件
condition的功能
接口condition把object的監(jiān)視器方法wait和notify分離出來,使得一個對象可以有多個等待的條件來執(zhí)行等待,配合lock的newcondition來實現(xiàn)。
- await:使當(dāng)前線程休眠,不可調(diào)度。這四種情況下會恢復(fù) 1:其它線程調(diào)用了signal,當(dāng)前線程恰好被選中了恢復(fù)執(zhí)行;2: 其它線程調(diào)用了signalall;3:其它線程中斷了當(dāng)前線程 4:spurious wakeup (假醒)。無論什么情況,在await方法返回之前,當(dāng)前線程必須重新獲取鎖
- awaituninterruptibly:使當(dāng)前線程休眠,不可調(diào)度。這三種情況下會恢復(fù) 1:其它線程調(diào)用了signal,當(dāng)前線程恰好被選中了恢復(fù)執(zhí)行;2: 其它線程調(diào)用了signalall;3:spurious wakeup (假醒)。
- awaitnanos:使當(dāng)前線程休眠,不可調(diào)度。這四種情況下會恢復(fù) 1:其它線程調(diào)用了signal,當(dāng)前線程恰好被選中了恢復(fù)執(zhí)行;2: 其它線程調(diào)用了signalall;3:其它線程中斷了當(dāng)前線程 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本身是個抽象類,負(fù)責(zé)手動lock和unlock,conditionobject則實現(xiàn)在父類abstractownablesynchronizer中,負(fù)責(zé)await與signal
sync的繼承結(jié)構(gòu)如下
sync的兩個實現(xiàn)類,公平鎖和非公平鎖
公平的鎖會把權(quán)限給等待時間最長的線程來執(zhí)行,非公平則獲取執(zhí)行權(quán)限的線程與線程本身的等待時間無關(guān)
默認(rèn)初始化reentrantlock使用的是非公平鎖,當(dāng)然可以通過指定參數(shù)來使用公平鎖
1
2
3
|
public reentrantlock() { sync = new nonfairsync(); } |
當(dāng)執(zhí)行獲取鎖時,實際就是去執(zhí)行 sync 的lock操作:
1
2
3
|
public void lock() { sync.lock(); } |
對應(yīng)在不同的鎖機(jī)制中有不同的實現(xiàn)
1、公平鎖實現(xiàn)
1
2
3
|
final void lock() { acquire( 1 ); } |
2、非公平鎖實現(xiàn)
1
2
3
4
5
6
|
final void lock() { if (compareandsetstate( 0 , 1 )) //先看當(dāng)前鎖是不是已經(jīng)被占有了,如果沒有,就直接將當(dāng)前線程設(shè)置為占有的線程 setexclusiveownerthread(thread.currentthread()); else acquire( 1 ); //鎖已經(jīng)被占有的情況下,嘗試獲取 } |
二者都調(diào)用父類abstractqueuedsynchronizer的方法
1
2
3
4
5
|
public final void acquire( int arg) { if (!tryacquire(arg) && acquirequeued(addwaiter(node.exclusive), arg)) //一旦搶失敗,就會進(jìn)入隊列,進(jìn)入隊列后則是依據(jù)fifo的原則來執(zhí)行喚醒 selfinterrupt(); } |
當(dāng)執(zhí)行unlock時,對應(yīng)方法在父類abstractqueuedsynchronizer中
1
2
3
4
5
6
7
8
9
|
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)機(jī)制則都是一樣的
公平鎖實現(xiàn)tryacquire
源碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
protected final boolean tryacquire( int acquires) { final thread current = thread.currentthread(); int c = getstate(); //獲取當(dāng)前的同步狀態(tài) if (c == 0 ) { //等于0 表示沒有被其它線程獲取過鎖 if (!hasqueuedpredecessors() && compareandsetstate( 0 , acquires)) { //hasqueuedpredecessors 判斷在當(dāng)前線程的前面是不是還有其它的線程,如果有,也就是鎖sync上有一個等待的線程,那么它不能獲取鎖,這意味著,只有等待時間最長的線程能夠獲取鎖,這就是是公平性的體現(xiàn) //compareandsetstate 看當(dāng)前在內(nèi)存中存儲的值是不是真的是0,如果是0就設(shè)置成accquires的取值。對于java,這種需要直接操作內(nèi)存的操作是通過unsafe來完成,具體的實現(xiàn)機(jī)制則依賴于操作系統(tǒng)。 //存儲獲取當(dāng)前鎖的線程 setexclusiveownerthread(current); return true ; } } else if (current == getexclusiveownerthread()) { //判斷是不是當(dāng)前線程獲取的鎖 int nextc = c + acquires; if (nextc < 0 ) //一個線程能夠獲取同一個鎖的次數(shù)是有限制的,就是int的最大值 throw new error( "maximum lock count exceeded" ); setstate(nextc); //在當(dāng)前的基礎(chǔ)上再增加一次鎖被持有的次數(shù) return true ; } //鎖被其它線程持有,獲取失敗 return false ; } |
非公平鎖實現(xiàn)tryacquire
獲取的關(guān)鍵實現(xiàn)為nonfairtryacquire
,源碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
final boolean nonfairtryacquire( int acquires) { final thread current = thread.currentthread(); int c = getstate(); if (c == 0 ) { //鎖沒有被持有 //可以看到這里會無視sync queue中是否有其它線程,只要執(zhí)行到了當(dāng)前線程,就會去獲取鎖 if (compareandsetstate( 0 , acquires)) { setexclusiveownerthread(current); //在判斷一次是不是鎖沒有被占有,沒有就去標(biāo)記當(dāng)前線程擁有這個鎖了 return true ; } } else if (current == getexclusiveownerthread()) { int nextc = c + acquires; if (nextc < 0 ) // overflow throw new error( "maximum lock count exceeded" ); setstate(nextc); //如果當(dāng)前線程已經(jīng)占有過,增加占有的次數(shù) return true ; } return false ; } |
釋放鎖的機(jī)制
1
2
3
4
5
6
7
8
9
10
11
12
13
|
protected final boolean tryrelease( int releases) { int c = getstate() - releases; if (thread.currentthread() != getexclusiveownerthread()) //只能是線程擁有這釋放 throw new illegalmonitorstateexception(); boolean free = false ; if (c == 0 ) { //當(dāng)占有次數(shù)為0的時候,就認(rèn)為所有的鎖都釋放完畢了 free = true ; setexclusiveownerthread( null ); } setstate(c); //更新鎖的狀態(tài) return free; } |
從源碼的實現(xiàn)可以看到
reentrantlock獲取鎖時,在鎖已經(jīng)被占有的情況下,如果占有鎖的線程是當(dāng)前線程,那么允許重入,即再次占有,如果由其它線程占有,則獲取失敗,由此可見,reetrantlock本身對鎖的持有是可重入的,同時是線程獨占的
。
公平與非公平就體現(xiàn)在,當(dāng)執(zhí)行的線程去獲取鎖的時候,公平的會去看是否有等待時間比它更長的,而非公平的就優(yōu)先直接去占有鎖
reentrantlock的trylock()與trylock(long timeout, timeunit unit):
1
2
3
4
|
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)置鎖功能上有一定的局限性,它無法響應(yīng)中斷,不能設(shè)置等待的時間
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000017134892