CountDownLatch 介绍与举例实现
生活随笔
收集整理的這篇文章主要介紹了
CountDownLatch 介绍与举例实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 概述
- 主要方法
- 舉例實現
概述
CountDownLatch 是 JUC 包下的一個重要的并發工具,它是一個線程協同作業的工具,使某些線程一直處于等待狀態,直到另外的線程完成任務后再執行。
主要方法
CountDownLatch 主要靠內部的一個計數器來實現同步功能,其過程具有不可重復性。
- countDown() 方法:計數器的值 -1。
- getCount() 方法:獲取當前計數器的值。
- await() 方法:當計數器的值不為 0 時,將阻塞所有調用此方法的線程,一直到計數器的值為 0 時,才會喚醒所有被此 CountDownLatch 對象阻塞的線程。
- await(long timeout, TimeUnit unit) 方法:在 await() 方法的基礎上,增加了超時時間,以及增加了 boolean 類型的返回值。
- 當 timeout 的值小于或等于 0 時,將不會等待,若此時計數器的值為 0 ,則返回 true,否則返回 false。
- 當計數器在超時時間內,值歸 0 了,則會正常返回 true,并執行喚醒操作。
- 當超過了這個超時時間,計數器的值還未歸 0,則會返回 false,也會執行喚醒操作。
舉例實現
現有代碼如下:
static class MyRunnable implements Runnable {private int id;private CountDownLatch countDownLatch;public MyRunnable(int id, CountDownLatch countDownLatch) {this.id = id;this.countDownLatch = countDownLatch;}@Overridepublic void run() {System.out.println("線程 :"+id+"正在執行......");try {Thread.sleep((int)(2000+(Math.random()*1000)));}catch (Exception ignored) {}countDownLatch.countDown();System.out.println("線程 :"+id+"執行結束!!!!!!");}}static class Runnable1 implements Runnable {private CountDownLatch countDownLatch;public Runnable1(CountDownLatch countDownLatch) {this.countDownLatch = countDownLatch;}@Overridepublic void run() {System.out.println("線程 Runnable 1 開始執行, 需要等到 CountDownLatch 的計數為0時才會執行下一步操作");try {countDownLatch.await();System.out.println("線程 Runnable 1 終于執行完畢, 此時 CountDownLatch 中的計數為: "+countDownLatch.getCount());} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) throws InterruptedException {CountDownLatch countDownLatch = new CountDownLatch(5);new Thread(new Runnable1(countDownLatch)).start();for (int i = 0;i<5;i++) {new Thread(new MyRunnable(i, countDownLatch)).start();}countDownLatch.await();System.out.println("全部線程執行結束, 現在主線程可以開始執行下一步操作, 此時 CountDownLatch 中的計數為: "+countDownLatch.getCount());}代碼運行結果為:
線程 Runnable 1 開始執行, 需要等到 CountDownLatch 的計數為0時才會執行下一步操作 線程 :0正在執行...... 線程 :2正在執行...... 線程 :3正在執行...... 線程 :4正在執行...... 線程 :1正在執行...... 線程 :3執行結束!!!!!! 線程 :2執行結束!!!!!! 線程 :1執行結束!!!!!! 線程 :0執行結束!!!!!! 線程 :4執行結束!!!!!! 線程 Runnable 1 終于執行完畢, 此時 CountDownLatch 中的計數為: 0 全部線程執行結束, 現在主線程可以開始執行下一步操作, 此時 CountDownLatch 中的計數為: 0可以看到,Runnable1 中的 run() 方法中的第一行打印語句最先執行,隨后調用 countDownLatch.await() 方法后即被阻塞 ,其后一直等到所有的 MyRunnable 線程都執行結束后(即 CountDownLatch 的內部計數器值為 0 時),第二行打印語句才被執行。主線程中的打印語句亦如此。
總結
以上是生活随笔為你收集整理的CountDownLatch 介绍与举例实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 空中最亮的星用计算机弹数字,赤峰——夜空
- 下一篇: HBase 简介