激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|JavaScript|易語言|

服務器之家 - 編程語言 - Java教程 - Java中的顯示鎖ReentrantLock使用與原理詳解

Java中的顯示鎖ReentrantLock使用與原理詳解

2021-06-17 11:13爬蜥 Java教程

這篇文章主要介紹了Java中的顯示鎖ReentrantLock使用與原理詳解,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

考慮一個場景,輪流打印0-100以內的技術和偶數。通過使用 synchronize 的 wait,notify機制就可以實現,核心思路如下:
使用兩個線程,一個打印奇數,一個打印偶數。這兩個線程會共享一個數據,數據每次自增,當打印奇數的線程發現當前要打印的數字不是奇數時,執行等待,否則打印奇數,并將數字自增1,對于打印偶數的線程也是如此

?
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
//打印奇數的線程
private static class oldrunner implements runnable{
  private mynumber n;
 
  public oldrunner(mynumber n) {
    this.n = n;
  }
 
  public void run() {
    while (true){
      n.waittoold(); //等待數據變成奇數
      system.out.println("old:" + n.getval());
      n.increase();
      if (n.getval()>98){
        break;
      }
    }
  }
}
//打印偶數的線程
private static class evenrunner implements runnable{
  private mynumber n;
 
  public evenrunner(mynumber n) {
    this.n = n;
  }
 
  public void run() {
    while (true){
      n.waittoeven();      //等待數據變成偶數
      system.out.println("even:"+n.getval());
      n.increase();
      if (n.getval()>99){
        break;
      }
    }
  }
}

共享的數據如下

?
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(); //數據變了,喚醒另外的線程
  }
  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(); //只要是偶數,一直等待
      } 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(); //只要是奇數,一直等待
      } 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();

運行結果如下

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機制,同樣可以使用顯示鎖來實現,兩個打印的線程還是同一個線程,只是使用的是顯示鎖來控制等待事件

?
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();//執行等待
        } catch (interruptedexception e) {
          e.printstacktrace();
        }
      }
    }finally {
      lock.unlock(); //顯示的釋放
    }
 
  }
}

同樣可以得到上述的效果

顯示鎖的功能

顯示鎖在java中通過接口lock提供如下功能

Java中的顯示鎖ReentrantLock使用與原理詳解

lock: 線程無法獲取鎖會進入休眠狀態,直到獲取成功

  • lockinterruptibly: 如果獲取成功,立即返回,否則一直休眠到線程被中斷或者是獲取成功
  • trylock:不會造成線程休眠,方法執行會立即返回,獲取到了鎖,返回true,否則返回false
  • trylock(long time, timeunit unit) throws interruptedexception : 在等待時間內沒有發生過中斷,并且沒有獲取鎖,就一直等待,當獲取到了,或者是線程中斷了,或者是超時時間到了這三者發生一個就返回,并記錄是否有獲取到鎖
  • unlock:釋放鎖
  • newcondition:每次調用創建一個鎖的等待條件,也就是說一個鎖可以擁有多個條件

condition的功能

接口condition把object的監視器方法wait和notify分離出來,使得一個對象可以有多個等待的條件來執行等待,配合lock的newcondition來實現。

  • await:使當前線程休眠,不可調度。這四種情況下會恢復 1:其它線程調用了signal,當前線程恰好被選中了恢復執行;2: 其它線程調用了signalall;3:其它線程中斷了當前線程 4:spurious wakeup (假醒)。無論什么情況,在await方法返回之前,當前線程必須重新獲取鎖
  • awaituninterruptibly:使當前線程休眠,不可調度。這三種情況下會恢復 1:其它線程調用了signal,當前線程恰好被選中了恢復執行;2: 其它線程調用了signalall;3:spurious wakeup (假醒)。
  • awaitnanos:使當前線程休眠,不可調度。這四種情況下會恢復 1:其它線程調用了signal,當前線程恰好被選中了恢復執行;2: 其它線程調用了signalall;3:其它線程中斷了當前線程 4:spurious wakeup (假醒)。5:超時了
  • await(long time, timeunit unit) :與awaitnanos類似,只是換了個時間單位
  • awaituntil(date deadline):與awaitnanos相似,只是指定日期之后返回,而不是指定的一段時間
  • signal:喚醒一個等待的線程
  • signalall:喚醒所有等待的線程

reentrantlock

從源碼中可以看到,reentrantlock的所有實現全都依賴于內部類sync和conditionobject。

sync本身是個抽象類,負責手動lock和unlock,conditionobject則實現在父類abstractownablesynchronizer中,負責await與signal

sync的繼承結構如下

Java中的顯示鎖ReentrantLock使用與原理詳解

sync的兩個實現類,公平鎖和非公平鎖

公平的鎖會把權限給等待時間最長的線程來執行,非公平則獲取執行權限的線程與線程本身的等待時間無關

默認初始化reentrantlock使用的是非公平鎖,當然可以通過指定參數來使用公平鎖

?
1
2
3
public reentrantlock() {
  sync = new nonfairsync();
}

當執行獲取鎖時,實際就是去執行 sync 的lock操作:

?
1
2
3
public void lock() {
  sync.lock();
}

對應在不同的鎖機制中有不同的實現

1、公平鎖實現

?
1
2
3
final void lock() {
  acquire(1);
}

2、非公平鎖實現

?
1
2
3
4
5
6
final void lock() {
  if (compareandsetstate(0, 1)) //先看當前鎖是不是已經被占有了,如果沒有,就直接將當前線程設置為占有的線程
    setexclusiveownerthread(thread.currentthread());
  else   
    acquire(1); //鎖已經被占有的情況下,嘗試獲取
}

二者都調用父類abstractqueuedsynchronizer的方法

?
1
2
3
4
5
public final void acquire(int arg) {
  if (!tryacquire(arg) &&
    acquirequeued(addwaiter(node.exclusive), arg)) //一旦搶失敗,就會進入隊列,進入隊列后則是依據fifo的原則來執行喚醒
    selfinterrupt();
}

當執行unlock時,對應方法在父類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 做了實現,而tryrelease的實現機制則都是一樣的

公平鎖實現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(); //獲取當前的同步狀態
  if (c == 0) {
    //等于0 表示沒有被其它線程獲取過鎖
    if (!hasqueuedpredecessors() &&
      compareandsetstate(0, acquires)) {
      //hasqueuedpredecessors 判斷在當前線程的前面是不是還有其它的線程,如果有,也就是鎖sync上有一個等待的線程,那么它不能獲取鎖,這意味著,只有等待時間最長的線程能夠獲取鎖,這就是是公平性的體現
      //compareandsetstate 看當前在內存中存儲的值是不是真的是0,如果是0就設置成accquires的取值。對于java,這種需要直接操作內存的操作是通過unsafe來完成,具體的實現機制則依賴于操作系統。
      //存儲獲取當前鎖的線程
      setexclusiveownerthread(current);
      return true;
    }
  }
  else if (current == getexclusiveownerthread()) {
    //判斷是不是當前線程獲取的鎖
    int nextc = c + acquires;
    if (nextc < 0)//一個線程能夠獲取同一個鎖的次數是有限制的,就是int的最大值
      throw new error("maximum lock count exceeded");
    setstate(nextc); //在當前的基礎上再增加一次鎖被持有的次數
    return true;
  }
  //鎖被其它線程持有,獲取失敗
  return false;
}

非公平鎖實現tryacquire

獲取的關鍵實現為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中是否有其它線程,只要執行到了當前線程,就會去獲取鎖
    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);//如果當前線程已經占有過,增加占有的次數
    return true;
  }
  return false;
}

釋放鎖的機制

?
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) {
    //當占有次數為0的時候,就認為所有的鎖都釋放完畢了
    free = true;
    setexclusiveownerthread(null);
  }
  setstate(c); //更新鎖的狀態
  return free;
}

從源碼的實現可以看到

reentrantlock獲取鎖時,在鎖已經被占有的情況下,如果占有鎖的線程是當前線程,那么允許重入,即再次占有,如果由其它線程占有,則獲取失敗,由此可見,reetrantlock本身對鎖的持有是可重入的,同時是線程獨占的

公平與非公平就體現在,當執行的線程去獲取鎖的時候,公平的會去看是否有等待時間比它更長的,而非公平的就優先直接去占有鎖

reentrantlock的trylock()與trylock(long timeout, timeunit unit):

?
1
2
3
4
public boolean trylock() {
//本質上就是執行一次非公平的搶鎖
return sync.nonfairtryacquire(1);
}

有時限的trylock核心代碼是 sync.tryacquirenanos(1, unit.tonanos(timeout));,由于有超時時間,它會直接放到等待隊列中,他與后面要講的aqs的lock原理中acquirequeued的區別在于park的時間是有限的,詳見源碼 abstractqueuedsynchronizer.doacquirenanos

為什么需要顯示鎖

內置鎖功能上有一定的局限性,它無法響應中斷,不能設置等待的時間

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

原文鏈接:https://segmentfault.com/a/1190000017134892

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 成人免费观看av | h视频免费观看 | 9191久久久久视频 | 日韩黄在线 | 久久精品一级片 | 色诱亚洲精品久久久久久 | 亚洲成人午夜精品 | 国内自拍网址 | 特色一级黄色片 | 毛片一区二区三区四区 | 国产91中文字幕 | 成人三级电影网址 | 黄色视频a级毛片 | 吾色视频 | 日日摸夜夜添夜夜添牛牛 | 国产精品一区在线观看 | 一本色道久久99精品综合蜜臀 | 一区二区免费看 | 一色桃子av大全在线播放 | 久久精品一区二区三区不卡牛牛 | 欧美一级α | 福利免费在线观看 | 视频一区 中文字幕 | 成人欧美日韩一区二区三区 | 免费看性xxx高清视频自由 | 国产女同疯狂激烈互摸 | 黄色特级片黄色特级片 | xxxx69hd一hd| 欧美日韩夜夜 | 国内精品伊人久久 | 一级在线 | 亚洲最新色 | 涩涩操| 久久免费视频3 | 亚洲精品欧美二区三区中文字幕 | videos韩国 | 护士hd欧美free性xxxx | 国产精品一品二区三区四区18 | 91九色视频在线播放 | av手机在线免费播放 | 日本视频网 |