最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java多線程并發(fā)編程(互斥鎖Reentrant Lock)

 更新時(shí)間:2017年05月22日 23:42:01   投稿:mdxy-dxy  
這篇文章主要介紹了ReentrantLock 互斥鎖,在同一時(shí)間只能被一個(gè)線程所占有,在被持有后并未釋放之前,其他線程若想獲得該鎖只能等待或放棄,需要的朋友可以參考下

Java 中的鎖通常分為兩種:

通過(guò)關(guān)鍵字 synchronized 獲取的鎖,我們稱為同步鎖,上一篇有介紹到:Java 多線程并發(fā)編程 Synchronized 關(guān)鍵字
java.util.concurrent(JUC)包里的鎖,如通過(guò)繼承接口 Lock 而實(shí)現(xiàn)的 ReentrantLock(互斥鎖),繼承 ReadWriteLock 實(shí)現(xiàn)的 ReentrantReadWriteLock(讀寫鎖)。
本篇主要介紹 ReentrantLock(互斥鎖)。

ReentrantLock(互斥鎖)

ReentrantLock 互斥鎖,在同一時(shí)間只能被一個(gè)線程所占有,在被持有后并未釋放之前,其他線程若想獲得該鎖只能等待或放棄。

ReentrantLock 互斥鎖是可重入鎖,即某一線程可多次獲得該鎖。

公平鎖 and 非公平鎖

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

  public ReentrantLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
  }

由 ReentrantLock 的構(gòu)造函數(shù)可見,在實(shí)例化 ReentrantLock 的時(shí)候我們可以選擇實(shí)例化一個(gè)公平鎖或非公平鎖,而默認(rèn)會(huì)構(gòu)造一個(gè)非公平鎖。

公平鎖與非公平鎖區(qū)別在于競(jìng)爭(zhēng)鎖時(shí)的有序與否。公平鎖可確保有序性(FIFO 隊(duì)列),非公平鎖不能確保有序性(即使也有 FIFO 隊(duì)列)。

然而,公平是要付出代價(jià)的,公平鎖比非公平鎖要耗性能,所以在非必須確保公平的條件下,一般使用非公平鎖可提高吞吐率。所以 ReentrantLock 默認(rèn)的構(gòu)造函數(shù)也是“不公平”的。

一般使用

DEMO1:

public class Test {

  private static class Counter {

    private ReentrantLock mReentrantLock = new ReentrantLock();

    public void count() {
      mReentrantLock.lock();
      try {
        for (int i = 0; i < 6; i++) {
          System.out.println(Thread.currentThread().getName() + ", i = " + i);
        }
      } finally {
	      // 必須在 finally 釋放鎖
        mReentrantLock.unlock();
      }
    }
  }

  private static class MyThread extends Thread {

    private Counter mCounter;

    public MyThread(Counter counter) {
      mCounter = counter;
    }

    @Override
    public void run() {
      super.run();
      mCounter.count();
    }
  }

  public static void main(String[] var0) {
    Counter counter = new Counter();
    // 注:myThread1 和 myThread2 是調(diào)用同一個(gè)對(duì)象 counter
    MyThread myThread1 = new MyThread(counter);
    MyThread myThread2 = new MyThread(counter);
    myThread1.start();
    myThread2.start();
  }
}

DEMO1 輸出:

Thread-0, i = 0
Thread-0, i = 1
Thread-0, i = 2
Thread-0, i = 3
Thread-0, i = 4
Thread-0, i = 5
Thread-1, i = 0
Thread-1, i = 1
Thread-1, i = 2
Thread-1, i = 3
Thread-1, i = 4
Thread-1, i = 5

DEMO1 僅使用了 ReentrantLock 的 lock 和 unlock 來(lái)提現(xiàn)一般鎖的特性,確保線程的有序執(zhí)行。此種場(chǎng)景 synchronized 也適用。

鎖的作用域

DEMO2:

public class Test {

  private static class Counter {

    private ReentrantLock mReentrantLock = new ReentrantLock();

    public void count() {
      for (int i = 0; i < 6; i++) {
        mReentrantLock.lock();
        // 模擬耗時(shí),突出線程是否阻塞
        try{
          Thread.sleep(100);
          System.out.println(Thread.currentThread().getName() + ", i = " + i);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
	        // 必須在 finally 釋放鎖
          mReentrantLock.unlock();
        }
      }
    }

    public void doOtherThing(){
      for (int i = 0; i < 6; i++) {
        // 模擬耗時(shí),突出線程是否阻塞
        try {
          Thread.sleep(100);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " doOtherThing, i = " + i);
      }
    }
  }
  
  public static void main(String[] var0) {
    final Counter counter = new Counter();
    new Thread(new Runnable() {
      @Override
      public void run() {
        counter.count();
      }
    }).start();
    new Thread(new Runnable() {
      @Override
      public void run() {
        counter.doOtherThing();
      }
    }).start();
  }
}

DEMO2 輸出:

Thread-0, i = 0
Thread-1 doOtherThing, i = 0
Thread-0, i = 1
Thread-1 doOtherThing, i = 1
Thread-0, i = 2
Thread-1 doOtherThing, i = 2
Thread-0, i = 3
Thread-1 doOtherThing, i = 3
Thread-0, i = 4
Thread-1 doOtherThing, i = 4
Thread-0, i = 5
Thread-1 doOtherThing, i = 5

DEMO3:

public class Test {

  private static class Counter {

    private ReentrantLock mReentrantLock = new ReentrantLock();

    public void count() {
      for (int i = 0; i < 6; i++) {
        mReentrantLock.lock();
        // 模擬耗時(shí),突出線程是否阻塞
        try{
          Thread.sleep(100);
          System.out.println(Thread.currentThread().getName() + ", i = " + i);
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          // 必須在 finally 釋放鎖
          mReentrantLock.unlock();
        }
      }
    }

    public void doOtherThing(){
      mReentrantLock.lock();
      try{
        for (int i = 0; i < 6; i++) {
          // 模擬耗時(shí),突出線程是否阻塞
          try {
            Thread.sleep(100);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          System.out.println(Thread.currentThread().getName() + " doOtherThing, i = " + i);
        }
      }finally {
        mReentrantLock.unlock();
      }

    }
  }

  public static void main(String[] var0) {
    final Counter counter = new Counter();
    new Thread(new Runnable() {
      @Override
      public void run() {
        counter.count();
      }
    }).start();
    new Thread(new Runnable() {
      @Override
      public void run() {
        counter.doOtherThing();
      }
    }).start();
  }
}

DEMO3 輸出:

Thread-0, i = 0
Thread-0, i = 1
Thread-0, i = 2
Thread-0, i = 3
Thread-0, i = 4
Thread-0, i = 5
Thread-1 doOtherThing, i = 0
Thread-1 doOtherThing, i = 1
Thread-1 doOtherThing, i = 2
Thread-1 doOtherThing, i = 3
Thread-1 doOtherThing, i = 4
Thread-1 doOtherThing, i = 5

結(jié)合 DEMO2 和 DEMO3 輸出可見,鎖的作用域在于 mReentrantLock,因?yàn)樗鶃?lái)自于 mReentrantLock。

可終止等待

DEMO4:

public class Test {

  static final int TIMEOUT = 300;

  private static class Counter {

    private ReentrantLock mReentrantLock = new ReentrantLock();

    public void count() {
      try{
        //lock() 不可中斷
        mReentrantLock.lock();
        // 模擬耗時(shí),突出線程是否阻塞
        for (int i = 0; i < 6; i++) {
          long startTime = System.currentTimeMillis();
          while (true) {
            if (System.currentTimeMillis() - startTime > 100)
              break;
          }
          System.out.println(Thread.currentThread().getName() + ", i = " + i);
        }
      } finally {
        // 必須在 finally 釋放鎖
        mReentrantLock.unlock();
      }
    }

    public void doOtherThing(){
      try{
        //lockInterruptibly() 可中斷,若線程沒(méi)有中斷,則獲取鎖
        mReentrantLock.lockInterruptibly();
        for (int i = 0; i < 6; i++) {
          // 模擬耗時(shí),突出線程是否阻塞
          long startTime = System.currentTimeMillis();
          while (true) {
            if (System.currentTimeMillis() - startTime > 100)
              break;
          }
          System.out.println(Thread.currentThread().getName() + " doOtherThing, i = " + i);
        }
      } catch (InterruptedException e) {
        System.out.println(Thread.currentThread().getName() + " 中斷 ");
      }finally {
        // 若當(dāng)前線程持有鎖,則釋放
        if(mReentrantLock.isHeldByCurrentThread()){
          mReentrantLock.unlock();
        }
      }
    }
  }

  public static void main(String[] var0) {
    final Counter counter = new Counter();
    new Thread(new Runnable() {
      @Override
      public void run() {
        counter.count();
      }
    }).start();
    Thread thread2 = new Thread(new Runnable() {
      @Override
      public void run() {
        counter.doOtherThing();
      }
    });
    thread2.start();
    long start = System.currentTimeMillis();
    while (true){
      if (System.currentTimeMillis() - start > TIMEOUT) {
        // 若線程還在運(yùn)行,嘗試中斷
        if(thread2.isAlive()){
          System.out.println(" 不等了,嘗試中斷 ");
          thread2.interrupt();
        }
        break;
      }
    }
  }
}

DEMO4 輸出:

Thread-0, i = 0
Thread-0, i = 1
Thread-0, i = 2
不等了,嘗試中斷
Thread-1 中斷
Thread-0, i = 3
Thread-0, i = 4
Thread-0, i = 5

線程 thread2 等待 300ms 后 timeout,中斷等待成功。

若把 TIMEOUT 改成 3000ms,輸出結(jié)果:(正常運(yùn)行)

Thread-0, i = 0
Thread-0, i = 1
Thread-0, i = 2
Thread-0, i = 3
Thread-0, i = 4
Thread-0, i = 5
Thread-1 doOtherThing, i = 0
Thread-1 doOtherThing, i = 1
Thread-1 doOtherThing, i = 2
Thread-1 doOtherThing, i = 3
Thread-1 doOtherThing, i = 4
Thread-1 doOtherThing, i = 5

定時(shí)鎖

DEMO5:

public class Test {

  static final int TIMEOUT = 3000;

  private static class Counter {

    private ReentrantLock mReentrantLock = new ReentrantLock();

    public void count() {
      try{
        //lock() 不可中斷
        mReentrantLock.lock();
        // 模擬耗時(shí),突出線程是否阻塞
        for (int i = 0; i < 6; i++) {
          long startTime = System.currentTimeMillis();
          while (true) {
            if (System.currentTimeMillis() - startTime > 100)
              break;
          }
          System.out.println(Thread.currentThread().getName() + ", i = " + i);
        }
      } finally {
        // 必須在 finally 釋放鎖
        mReentrantLock.unlock();
      }
    }

    public void doOtherThing(){
      try{
        //tryLock(long timeout, TimeUnit unit) 嘗試獲得鎖
        boolean isLock = mReentrantLock.tryLock(300, TimeUnit.MILLISECONDS);
        System.out.println(Thread.currentThread().getName() + " isLock:" + isLock);
        if(isLock){
          for (int i = 0; i < 6; i++) {
            // 模擬耗時(shí),突出線程是否阻塞
            long startTime = System.currentTimeMillis();
            while (true) {
              if (System.currentTimeMillis() - startTime > 100)
                break;
            }
            System.out.println(Thread.currentThread().getName() + " doOtherThing, i = " + i);
          }
        }else{
          System.out.println(Thread.currentThread().getName() + " timeout");
        }
      } catch (InterruptedException e) {
        System.out.println(Thread.currentThread().getName() + " 中斷 ");
      }finally {
        // 若當(dāng)前線程持有鎖,則釋放
        if(mReentrantLock.isHeldByCurrentThread()){
          mReentrantLock.unlock();
        }
      }
    }
  }

  public static void main(String[] var0) {
    final Counter counter = new Counter();
    new Thread(new Runnable() {
      @Override
      public void run() {
        counter.count();
      }
    }).start();
    Thread thread2 = new Thread(new Runnable() {
      @Override
      public void run() {
        counter.doOtherThing();
      }
    });
    thread2.start();
  }
}

DEMO5 輸出:

Thread-0, i = 0
Thread-0, i = 1
Thread-0, i = 2
Thread-1 isLock:false
Thread-1 timeout
Thread-0, i = 3
Thread-0, i = 4
Thread-0, i = 5

tryLock() 嘗試獲得鎖,tryLock(long timeout, TimeUnit unit) 在給定的 timeout 時(shí)間內(nèi)嘗試獲得鎖,若超時(shí),則不帶鎖往下走,所以必須加以判斷。

ReentrantLock or synchronized

ReentrantLock 、synchronized 之間如何選擇?

ReentrantLock 在性能上 比 synchronized 更勝一籌。

ReentrantLock 需格外小心,因?yàn)樾枰@式釋放鎖,lock() 后記得 unlock(),而且必須在 finally 里面,否則容易造成死鎖。
synchronized 隱式自動(dòng)釋放鎖,使用方便。

ReentrantLock 擴(kuò)展性好,可中斷鎖,定時(shí)鎖,自由控制。
synchronized 一但進(jìn)入阻塞等待,則無(wú)法中斷等待。

相關(guān)文章

  • jpanel設(shè)置背景圖片的二個(gè)小例子

    jpanel設(shè)置背景圖片的二個(gè)小例子

    這篇文章主要介紹了jpanel設(shè)置背景圖片的二個(gè)小例子,實(shí)現(xiàn)了動(dòng)態(tài)加載圖片做背景的方法,需要的朋友可以參考下
    2014-03-03
  • 輕松掌握J(rèn)ava建造者模式

    輕松掌握J(rèn)ava建造者模式

    這篇文章主要幫助大家輕松掌握J(rèn)ava建造者模式,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • 完美解決Server?returned?HTTP?response?code:403?for?URL報(bào)錯(cuò)問(wèn)題

    完美解決Server?returned?HTTP?response?code:403?for?URL報(bào)錯(cuò)問(wèn)題

    在調(diào)用某個(gè)接口的時(shí)候,突然就遇到了Server?returned?HTTP?response?code:?403?for?URL報(bào)錯(cuò)這個(gè)報(bào)錯(cuò),導(dǎo)致獲取不到接口的數(shù)據(jù),下面小編給大家分享解決Server?returned?HTTP?response?code:403?for?URL報(bào)錯(cuò)問(wèn)題,感興趣的朋友一起看看吧
    2023-03-03
  • SpringBoot Scheduling定時(shí)任務(wù)的示例代碼

    SpringBoot Scheduling定時(shí)任務(wù)的示例代碼

    springBoot提供了定時(shí)任務(wù)的支持,通過(guò)注解簡(jiǎn)單快捷,對(duì)于日常定時(shí)任務(wù)可以使用。本文詳細(xì)的介紹一下使用,感興趣的可以了解一下
    2021-08-08
  • spring @AfterReturning返回值問(wèn)題

    spring @AfterReturning返回值問(wèn)題

    這篇文章主要介紹了spring @AfterReturning返回值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Myeclipse 2016下Aptana安裝教程

    Myeclipse 2016下Aptana安裝教程

    這篇文章主要為大家詳細(xì)介紹了Myeclipse 2016下Aptana安裝教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-05-05
  • Spring Boot中使用RabbitMQ的示例代碼

    Spring Boot中使用RabbitMQ的示例代碼

    本篇文章主要介紹了Spring Boot中使用RabbitMQ的示例代碼,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2018-04-04
  • 認(rèn)證授權(quán)中解決AuthenticationManager無(wú)法注入問(wèn)題

    認(rèn)證授權(quán)中解決AuthenticationManager無(wú)法注入問(wèn)題

    這篇文章主要介紹了認(rèn)證授權(quán)中解決AuthenticationManager無(wú)法注入問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-10-10
  • Java中String字符串使用避坑指南

    Java中String字符串使用避坑指南

    Java中的String字符串是我們?nèi)粘>幊讨杏玫米疃嗟念愔?看似簡(jiǎn)單的String使用,卻隱藏著不少“坑”,如果不注意,可能會(huì)導(dǎo)致性能問(wèn)題、意外的錯(cuò)誤容易造成線上事故( OOM),服務(wù)器崩潰,甚至難以察覺(jué)的Bug!今天我們就來(lái)聊聊String使用中的一些常見坑點(diǎn),以及如何優(yōu)雅避坑
    2025-02-02
  • Java裝飾者模式實(shí)例詳解

    Java裝飾者模式實(shí)例詳解

    這篇文章主要介紹了Java裝飾者模式,結(jié)合實(shí)例形式詳細(xì)分析了裝飾著模式的原理與java具體實(shí)現(xiàn)技巧,需要的朋友可以參考下
    2017-09-09

最新評(píng)論

奉贤区| 南平市| 六枝特区| 山阳县| 萨迦县| 谷城县| 会宁县| 黄大仙区| 新竹市| 增城市| 尤溪县| 绩溪县| 南澳县| 景谷| 富源县| 文昌市| 诸城市| 玉山县| 应城市| 丰都县| 和平区| 周口市| 古蔺县| 大荔县| 平定县| 澄城县| 文山县| 社旗县| 喀喇| 高邑县| 马关县| 浪卡子县| 华安县| 抚宁县| 新巴尔虎右旗| 北海市| 封开县| 泌阳县| 博湖县| 兰考县| 凤城市|