Java的concurrent包里面的CountDownLatch其實(shí)可以把它看作一個(gè)計(jì)數(shù)器结借,只不過這個(gè)計(jì)數(shù)器的操作是原子操作,同時(shí)只能有一個(gè)線程去操作這個(gè)計(jì)數(shù)器卒茬,也就是同時(shí)只能有一個(gè)線程去減這個(gè)計(jì)數(shù)器里面的值船老。
你可以向CountDownLatch對(duì)象設(shè)置一個(gè)初始的數(shù)字作為計(jì)數(shù)值,任何調(diào)用這個(gè)對(duì)象上的await()方法都會(huì)阻塞扬虚,直到這個(gè)計(jì)數(shù)器的計(jì)數(shù)值被其他的線程減為0為止努隙。
CountDownLatch的一個(gè)非常典型的應(yīng)用場(chǎng)景是:有一個(gè)任務(wù)想要往下執(zhí)行,但必須要等到其他的任務(wù)執(zhí)行完畢后才可以繼續(xù)往下執(zhí)行辜昵。假如我們這個(gè)想要繼續(xù)往下執(zhí)行的任務(wù)調(diào)用一個(gè)CountDownLatch對(duì)象的await()方法荸镊,其他的任務(wù)執(zhí)行完自己的任務(wù)后調(diào)用同一個(gè)CountDownLatch對(duì)象上的countDown()方法,這個(gè)調(diào)用await()方法的任務(wù)將一直阻塞等待,直到這個(gè)CountDownLatch對(duì)象的計(jì)數(shù)值減到0為止躬存。
舉個(gè)例子张惹,有三個(gè)工人在為老板干活,這個(gè)老板有一個(gè)習(xí)慣岭洲,就是當(dāng)三個(gè)工人把一天的活都干完了的時(shí)候宛逗,他就來檢查所有工人所干的活。記住這個(gè)條件:三個(gè)工人先全部干完活盾剩,老板才檢查雷激。所以在這里用Java代碼設(shè)計(jì)兩個(gè)類,Worker代表工人告私,Boss代表老板屎暇,具體的代碼實(shí)現(xiàn)如下:
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("工人活都干完了驻粟,老板開始檢查了根悼!");
}
}
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();
}
}
當(dāng)你運(yùn)行CountDownLatchDemo這個(gè)對(duì)象的時(shí)候,你會(huì)發(fā)現(xiàn)是等所有的工人都干完了活蜀撑,老板才來檢查挤巡,下面是我本地機(jī)器上運(yùn)行的一次結(jié)果,可以肯定的每次運(yùn)行的結(jié)果可能與下面不一樣酷麦,但老板檢查永遠(yuǎn)是在后面的矿卑。
王二正在干活!
李四正在干活!
老板正在等所有的工人干完活......
張三正在干活!
張三活干完了!
王二活干完了贴铜!
李四活干完了粪摘!
工人活都干完了,老板開始檢查了绍坝!