Java的concurrent包裏面的CountDownLatch其實能夠把它看做一個計數器,只不過這個計數器的操做是原子操做,同時只能有一個線程去操做這個計數器,也就是同時只能有一個線程去減這個計數器裏面的值。java
你能夠向CountDownLatch對象設置一個初始的數字做爲計數值,任何調用這個對象上的await()方法都會阻塞,直到這個計數器的計數值被其餘的線程減爲0爲止。dom
CountDownLatch的一個很是典型的應用場景是:有一個任務想要往下執行,但必需要等到其餘的任務執行完畢後才能夠繼續往下執行。假如咱們這個想要繼續往下執行的任務調用一個CountDownLatch對象的await()方法,其餘的任務執行完本身的任務後調用同一個CountDownLatch對象上的countDown()方法,這個調用await()方法的任務將一直阻塞等待,直到這個CountDownLatch對象的計數值減到0爲止。this
舉個例子,有三個工人在爲老闆幹活,這個老闆有一個習慣,就是當三個工人把一天的活都幹完了的時候,他就來檢查全部工人所幹的活。記住這個條件:三個工人先所有幹完活,老闆才檢查。因此在這裏用Java代碼設計兩個類,Worker表明工人,Boss表明老闆,具體的代碼實現以下:spa
worker 工人類線程
package org.zapldy.concurrent; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class Worker implements Runnable{ private CountDownLatch downLatch; private String name; public Worker(CountDownLatch downLatch, String name){ this.downLatch = downLatch; this.name = name; } public void run() { this.doWork(); try{ TimeUnit.SECONDS.sleep(new Random().nextInt(10)); }catch(InterruptedException ie){ } System.out.println(this.name + "活幹完了!"); this.downLatch.countDown(); } private void doWork(){ System.out.println(this.name + "正在幹活!"); } }
boss 工人
設計
package org.zapldy.concurrent; import java.util.concurrent.CountDownLatch; public class Boss implements Runnable { private CountDownLatch downLatch; public Boss(CountDownLatch downLatch){ this.downLatch = downLatch; } public void run() { System.out.println("老闆正在等全部的工人幹完活......"); try { this.downLatch.await(); } catch (InterruptedException e) { } System.out.println("工人活都幹完了,老闆開始檢查了!"); } }
執行類code
package org.zapldy.concurrent; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchDemo { public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(3); Worker w1 = new Worker(latch,"張三"); Worker w2 = new Worker(latch,"李四"); Worker w3 = new Worker(latch,"王二"); Boss boss = new Boss(latch); executor.execute(w3); executor.execute(w2); executor.execute(w1); executor.execute(boss); executor.shutdown(); } }
當你運行CountDownLatchDemo這個對象的時候,你會發現是等全部的工人都幹完了活,老闆纔來檢查,下面是我本地機器上運行的一次結果,能夠確定的每次運行的結果可能與下面不同,但老闆檢查永遠是在後面的。orm
老闆正在等全部的工人幹完活...... 張三正在幹活! 李四正在幹活! 王二正在幹活! 張三活幹完了! 李四活幹完了! 王二活幹完了! 工人活都幹完了,老闆開始檢查了!