亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2018年11月26日 11:18:56   作者:爬蜥  
這篇文章主要介紹了Java中的顯示鎖ReentrantLock使用與原理詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

考慮一個(gè)場(chǎng)景,輪流打印0-100以?xún)?nèi)的技術(shù)和偶數(shù)。通過(guò)使用 synchronize 的 wait,notify機(jī)制就可以實(shí)現(xiàn),核心思路如下:
使用兩個(gè)線程,一個(gè)打印奇數(shù),一個(gè)打印偶數(shù)。這兩個(gè)線程會(huì)共享一個(gè)數(shù)據(jù),數(shù)據(jù)每次自增,當(dāng)打印奇數(shù)的線程發(fā)現(xiàn)當(dāng)前要打印的數(shù)字不是奇數(shù)時(shí),執(zhí)行等待,否則打印奇數(shù),并將數(shù)字自增1,對(duì)于打印偶數(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();
      }
    }
  }
}

運(yùn)行代碼如下

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();

運(yùn)行結(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ī)制,同樣可以使用顯示鎖來(lái)實(shí)現(xiàn),兩個(gè)打印的線程還是同一個(gè)線程,只是使用的是顯示鎖來(lái)控制等待事件

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中通過(guò)接口Lock提供如下功能

lock: 線程無(wú)法獲取鎖會(huì)進(jìn)入休眠狀態(tài),直到獲取成功

  • lockInterruptibly: 如果獲取成功,立即返回,否則一直休眠到線程被中斷或者是獲取成功
  • tryLock:不會(huì)造成線程休眠,方法執(zhí)行會(huì)立即返回,獲取到了鎖,返回true,否則返回false
  • tryLock(long time, TimeUnit unit) throws InterruptedException : 在等待時(shí)間內(nèi)沒(méi)有發(fā)生過(guò)中斷,并且沒(méi)有獲取鎖,就一直等待,當(dāng)獲取到了,或者是線程中斷了,或者是超時(shí)時(shí)間到了這三者發(fā)生一個(gè)就返回,并記錄是否有獲取到鎖
  • unlock:釋放鎖
  • newCondition:每次調(diào)用創(chuàng)建一個(gè)鎖的等待條件,也就是說(shuō)一個(gè)鎖可以擁有多個(gè)條件

Condition的功能

接口Condition把Object的監(jiān)視器方法wait和notify分離出來(lái),使得一個(gè)對(duì)象可以有多個(gè)等待的條件來(lái)執(zhí)行等待,配合Lock的newCondition來(lái)實(shí)現(xiàn)。

  • await:使當(dāng)前線程休眠,不可調(diào)度。這四種情況下會(huì)恢復(fù) 1:其它線程調(diào)用了signal,當(dāng)前線程恰好被選中了恢復(fù)執(zhí)行;2: 其它線程調(diào)用了signalAll;3:其它線程中斷了當(dāng)前線程 4:spurious wakeup (假醒)。無(wú)論什么情況,在await方法返回之前,當(dāng)前線程必須重新獲取鎖
  • awaitUninterruptibly:使當(dāng)前線程休眠,不可調(diào)度。這三種情況下會(huì)恢復(fù) 1:其它線程調(diào)用了signal,當(dāng)前線程恰好被選中了恢復(fù)執(zhí)行;2: 其它線程調(diào)用了signalAll;3:spurious wakeup (假醒)。
  • awaitNanos:使當(dāng)前線程休眠,不可調(diào)度。這四種情況下會(huì)恢復(fù) 1:其它線程調(diào)用了signal,當(dāng)前線程恰好被選中了恢復(fù)執(zhí)行;2: 其它線程調(diào)用了signalAll;3:其它線程中斷了當(dāng)前線程 4:spurious wakeup (假醒)。5:超時(shí)了
  • await(long time, TimeUnit unit) :與awaitNanos類(lèi)似,只是換了個(gè)時(shí)間單位
  • awaitUntil(Date deadline):與awaitNanos相似,只是指定日期之后返回,而不是指定的一段時(shí)間
  • signal:喚醒一個(gè)等待的線程
  • signalAll:喚醒所有等待的線程

ReentrantLock

從源碼中可以看到,ReentrantLock的所有實(shí)現(xiàn)全都依賴(lài)于內(nèi)部類(lèi)Sync和ConditionObject。

Sync本身是個(gè)抽象類(lèi),負(fù)責(zé)手動(dòng)lock和unlock,ConditionObject則實(shí)現(xiàn)在父類(lèi)AbstractOwnableSynchronizer中,負(fù)責(zé)await與signal

Sync的繼承結(jié)構(gòu)如下


Sync的兩個(gè)實(shí)現(xiàn)類(lèi),公平鎖和非公平鎖

公平的鎖會(huì)把權(quán)限給等待時(shí)間最長(zhǎng)的線程來(lái)執(zhí)行,非公平則獲取執(zhí)行權(quán)限的線程與線程本身的等待時(shí)間無(wú)關(guān)

默認(rèn)初始化ReentrantLock使用的是非公平鎖,當(dāng)然可以通過(guò)指定參數(shù)來(lái)使用公平鎖

public ReentrantLock() {
  sync = new NonfairSync();
}

當(dāng)執(zhí)行獲取鎖時(shí),實(shí)際就是去執(zhí)行 Sync 的lock操作:

public void lock() {
  sync.lock();
}

對(duì)應(yīng)在不同的鎖機(jī)制中有不同的實(shí)現(xiàn)

1、公平鎖實(shí)現(xiàn)

final void lock() {
  acquire(1);
}

2、非公平鎖實(shí)現(xiàn)

final void lock() {
  if (compareAndSetState(0, 1)) //先看當(dāng)前鎖是不是已經(jīng)被占有了,如果沒(méi)有,就直接將當(dāng)前線程設(shè)置為占有的線程
    setExclusiveOwnerThread(Thread.currentThread());
  else    
    acquire(1); //鎖已經(jīng)被占有的情況下,嘗試獲取
}

二者都調(diào)用父類(lèi)AbstractQueuedSynchronizer的方法

public final void acquire(int arg) {
  if (!tryAcquire(arg) &&
    acquireQueued(addWaiter(Node.EXCLUSIVE), arg)) //一旦搶失敗,就會(huì)進(jìn)入隊(duì)列,進(jìn)入隊(duì)列后則是依據(jù)FIFO的原則來(lái)執(zhí)行喚醒
    selfInterrupt();
}

當(dāng)執(zhí)行unlock時(shí),對(duì)應(yīng)方法在父類(lèi)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;
}

公平鎖和非公平鎖則分別對(duì)獲取鎖的方式tryAcquire 做了實(shí)現(xiàn),而tryRelease的實(shí)現(xiàn)機(jī)制則都是一樣的

公平鎖實(shí)現(xiàn)tryAcquire

源碼如下

protected final boolean tryAcquire(int acquires) {
  final Thread current = Thread.currentThread();
  int c = getState(); //獲取當(dāng)前的同步狀態(tài)
  if (c == 0) {
    //等于0 表示沒(méi)有被其它線程獲取過(guò)鎖
    if (!hasQueuedPredecessors() &&
      compareAndSetState(0, acquires)) {
      //hasQueuedPredecessors 判斷在當(dāng)前線程的前面是不是還有其它的線程,如果有,也就是鎖sync上有一個(gè)等待的線程,那么它不能獲取鎖,這意味著,只有等待時(shí)間最長(zhǎng)的線程能夠獲取鎖,這就是是公平性的體現(xiàn)
      //compareAndSetState 看當(dāng)前在內(nèi)存中存儲(chǔ)的值是不是真的是0,如果是0就設(shè)置成accquires的取值。對(duì)于JAVA,這種需要直接操作內(nèi)存的操作是通過(guò)unsafe來(lái)完成,具體的實(shí)現(xiàn)機(jī)制則依賴(lài)于操作系統(tǒng)。
      //存儲(chǔ)獲取當(dāng)前鎖的線程
      setExclusiveOwnerThread(current);
      return true;
    }
  }
  else if (current == getExclusiveOwnerThread()) {
    //判斷是不是當(dāng)前線程獲取的鎖
    int nextc = c + acquires;
    if (nextc < 0)//一個(gè)線程能夠獲取同一個(gè)鎖的次數(shù)是有限制的,就是int的最大值
      throw new Error("Maximum lock count exceeded");
    setState(nextc); //在當(dāng)前的基礎(chǔ)上再增加一次鎖被持有的次數(shù)
    return true;
  }
  //鎖被其它線程持有,獲取失敗
  return false;
}

非公平鎖實(shí)現(xiàn)tryAcquire

獲取的關(guān)鍵實(shí)現(xiàn)為nonfairTryAcquire,源碼如下

final boolean nonfairTryAcquire(int acquires) {
  final Thread current = Thread.currentThread();
  int c = getState();
  if (c == 0) {
    //鎖沒(méi)有被持有
    //可以看到這里會(huì)無(wú)視sync queue中是否有其它線程,只要執(zhí)行到了當(dāng)前線程,就會(huì)去獲取鎖
    if (compareAndSetState(0, acquires)) { 
      setExclusiveOwnerThread(current); //在判斷一次是不是鎖沒(méi)有被占有,沒(méi)有就去標(biāo)記當(dāng)前線程擁有這個(gè)鎖了
      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)占有過(guò),增加占有的次數(shù)
    return true;
  }
  return false;
}

釋放鎖的機(jī)制

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的時(shí)候,就認(rèn)為所有的鎖都釋放完畢了
    free = true; 
    setExclusiveOwnerThread(null);
  }
  setState(c); //更新鎖的狀態(tài)
  return free;
}

從源碼的實(shí)現(xiàn)可以看到

ReentrantLock獲取鎖時(shí),在鎖已經(jīng)被占有的情況下,如果占有鎖的線程是當(dāng)前線程,那么允許重入,即再次占有,如果由其它線程占有,則獲取失敗,由此可見(jiàn),ReetrantLock本身對(duì)鎖的持有是可重入的,同時(shí)是線程獨(dú)占的

公平與非公平就體現(xiàn)在,當(dāng)執(zhí)行的線程去獲取鎖的時(shí)候,公平的會(huì)去看是否有等待時(shí)間比它更長(zhǎng)的,而非公平的就優(yōu)先直接去占有鎖

ReentrantLock的tryLock()與tryLock(long timeout, TimeUnit unit):

public boolean tryLock() {
//本質(zhì)上就是執(zhí)行一次非公平的搶鎖
return sync.nonfairTryAcquire(1); 
}

有時(shí)限的tryLock核心代碼是 sync.tryAcquireNanos(1, unit.toNanos(timeout));,由于有超時(shí)時(shí)間,它會(huì)直接放到等待隊(duì)列中,他與后面要講的AQS的lock原理中acquireQueued的區(qū)別在于park的時(shí)間是有限的,詳見(jiàn)源碼 AbstractQueuedSynchronizer.doAcquireNanos

為什么需要顯示鎖

內(nèi)置鎖功能上有一定的局限性,它無(wú)法響應(yīng)中斷,不能設(shè)置等待的時(shí)間

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java線程的基礎(chǔ)實(shí)例解析

    java線程的基礎(chǔ)實(shí)例解析

    java中線程的基本方法的熟練使用是精通多線程編程的必經(jīng)之路,線程相關(guān)的基本方法有wait,notify,notifyAll,sleep,join,yield等,本文淺要的介紹一下它們的使用方式
    2021-06-06
  • 關(guān)于Java中數(shù)組切片的幾種方法(獲取數(shù)組元素)

    關(guān)于Java中數(shù)組切片的幾種方法(獲取數(shù)組元素)

    這篇文章主要介紹了關(guān)于Java中數(shù)組切片的幾種方法(獲取數(shù)組元素),切片是數(shù)組的一個(gè)引用,因此切片是引用類(lèi)型,在進(jìn)行傳遞時(shí),遵守引用傳遞的機(jī)制,需要的朋友可以參考下
    2023-05-05
  • Spring中BeanUtils.copyProperties的坑及解決

    Spring中BeanUtils.copyProperties的坑及解決

    這篇文章主要介紹了Spring中BeanUtils.copyProperties的坑及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • 解決Intellij IDEA運(yùn)行報(bào)Command line is too long的問(wèn)題

    解決Intellij IDEA運(yùn)行報(bào)Command line is too long的問(wèn)題

    這篇文章主要介紹了解決Intellij IDEA運(yùn)行報(bào)Command line is too long的問(wèn)題,本文通過(guò)兩種方案給大家詳細(xì)介紹,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-05-05
  • Feign調(diào)用接口解決處理內(nèi)部異常的問(wèn)題

    Feign調(diào)用接口解決處理內(nèi)部異常的問(wèn)題

    這篇文章主要介紹了Feign調(diào)用接口解決處理內(nèi)部異常的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • Springboot整合Redis實(shí)現(xiàn)超賣(mài)問(wèn)題還原和流程分析(分布式鎖)

    Springboot整合Redis實(shí)現(xiàn)超賣(mài)問(wèn)題還原和流程分析(分布式鎖)

    最近在研究超賣(mài)的項(xiàng)目,寫(xiě)一段簡(jiǎn)單正常的超賣(mài)邏輯代碼,多個(gè)用戶同時(shí)操作同一段數(shù)據(jù)出現(xiàn)問(wèn)題,糾結(jié)該如何處理呢?下面小編給大家?guī)?lái)了Springboot整合Redis實(shí)現(xiàn)超賣(mài)問(wèn)題還原和流程分析,感興趣的朋友一起看看吧
    2021-10-10
  • mybatis動(dòng)態(tài)sql之Map參數(shù)的講解

    mybatis動(dòng)態(tài)sql之Map參數(shù)的講解

    今天小編就為大家分享一篇關(guān)于mybatis動(dòng)態(tài)sql之Map參數(shù)的講解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-03-03
  • 詳解如何用spring Restdocs創(chuàng)建API文檔

    詳解如何用spring Restdocs創(chuàng)建API文檔

    這篇文章將帶你了解如何用spring官方推薦的restdoc去生成api文檔。具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • Spring boot攔截器實(shí)現(xiàn)IP黑名單的完整步驟

    Spring boot攔截器實(shí)現(xiàn)IP黑名單的完整步驟

    這篇文章主要給大家介紹了關(guān)于Spring boot攔截器實(shí)現(xiàn)IP黑名單的完整步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring boot攔截器具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • Springboot?JPA如何使用distinct返回對(duì)象

    Springboot?JPA如何使用distinct返回對(duì)象

    這篇文章主要介紹了Springboot?JPA如何使用distinct返回對(duì)象,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02

最新評(píng)論