1.java
package com.test.frame.test.countDownLatch; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.CountDownLatch; /** * created by guanguan on 2017/10/26 **/ public class CountDownLatchDemo { final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); static class Worker extends Thread { private String workName; private int workTime; CountDownLatch latch; public Worker(String workName, int workTime, CountDownLatch latch) { this.workName = workName; this.workTime = workTime; this.latch = latch; } public Worker(Worker worker) { } @Override public void run() { System.out.println("worker : "+workName +"start begin at "+sdf.format(new Date())); doWork(); System.out.println("worker : "+workName +"start complete at "+sdf.format(new Date())); } private void doWork() { try { Thread.sleep(workTime); } catch (InterruptedException e) { e.printStackTrace(); }finally { latch.countDown();//工人完成工做,計數器減一 } } } public static void main(String[] args) throws InterruptedException { /** * 初始化CountDownLatch,將其值置爲2,latch計數器的操做是原子性的 */ CountDownLatch latch=new CountDownLatch(2); Worker worker1= new Worker("WORK-1",5000,latch); Worker worker2= new Worker("WORK-2",2000,latch); Worker worker3= new Worker("WORK-3",1000,latch); worker1.start(); latch.await(); //此時將永遠阻塞,由於只有一個線程開啓,完成任務 worker2.start(); worker3.start(); } } 運行結果是: worker : WORK-1start begin at 2017-10-26 14:32:54 worker : WORK-1start complete at 2017-10-26 14:32:59 此時因爲latch.await()的緣由,則線程將永遠阻塞,由於latch仍是1,沒有置爲0,則線程2,線程3將沒法進行 若是將 latch.await(); //此時將永遠阻塞,由於只有一個線程開啓,完成任務 worker2.start(); 這兩行對換, public static void main(String[] args) throws InterruptedException { CountDownLatch latch=new CountDownLatch(2);//兩個工人的協做 Worker worker1= new Worker("WORK-1",5000,latch); Worker worker2= new Worker("WORK-2",2000,latch); Worker worker3= new Worker("WORK-3",1000,latch); worker1.start(); worker2.start(); latch.await(); worker3.start(); } 運行結果以下: worker : WORK-2start begin at 2017-10-26 14:34:35 worker : WORK-1start begin at 2017-10-26 14:34:35 worker : WORK-2start complete at 2017-10-26 14:34:37 worker : WORK-1start complete at 2017-10-26 14:34:40 worker : WORK-3start begin at 2017-10-26 14:34:40 worker : WORK-3start complete at 2017-10-26 14:34:41 Process finished with exit code 0 代表線程1,線程2同時運行,並阻塞,而後1,2所有完成以後,線程3纔開始運行