CountDownLatch是一个同步辅助类,完成指定线程数量之前,同步等待其他线程完成,个人感觉和计数器差不多。
2.CountDownLatch示例
import java.util.concurrent.CountDownLatch; /** * Created by wuhao on 15-12-23. */ public class CountDownLatchDemo { public static void main(String[] args) { //计数器数值为3,工作线程数 CountDownLatch countDownLatch=new CountDownLatch(3); WorkThread workThread1 = new WorkThread(1, 10, "张三", countDownLatch); WorkThread workThread2 = new WorkThread(2, 1, "李四", countDownLatch); WorkThread workThread3 = new WorkThread(3, 4, "王五", countDownLatch); workThread1.start(); workThread2.start(); workThread3.start(); try { countDownLatch.await(); System.out.println("All Thread Complete: "); } catch (InterruptedException e) { System.out.println("countDownLatch.await() Error"); } } } class WorkThread extends Thread{ private int index; private int time; private String name; private CountDownLatch countDownLatch; public WorkThread(int index, int time , String name, CountDownLatch countDownLatch) { this.index = index; this.time = time; this.name = name; this.countDownLatch = countDownLatch; } @Override public void run() { System.out.println("Thread Index: " + index + ", Name: " + name + " Start"); try { Thread.sleep(time * 1000); } catch (InterruptedException e) { System.out.println("Thread.sleep(2000) Error"); } System.out.println("Thread Index: " + index + ", Name: " + name + " End"); countDownLatch.countDown(); //计数器-1 } }
输出结果:
1.计数器数值为3
Thread Index: 1, Name: 张三 Start Thread Index: 2, Name: 李四 Start Thread Index: 3, Name: 王五 Start Thread Index: 2, Name: 李四 End Thread Index: 3, Name: 王五 End Thread Index: 1, Name: 张三 End All Thread Complete: 三个工作线程结束后触发
2.计数器数值为2
Thread Index: 1, Name: 张三 Start Thread Index: 2, Name: 李四 Start Thread Index: 3, Name: 王五 Start Thread Index: 2, Name: 李四 End Thread Index: 3, Name: 王五 End All Thread Complete: Thread Index: 1, Name: 张三 End 两个工作线程结束后触发
3.计数器数值为4
Thread Index: 1, Name: 张三 Start Thread Index: 2, Name: 李四 Start Thread Index: 3, Name: 王五 Start Thread Index: 2, Name: 李四 End Thread Index: 3, Name: 王五 End Thread Index: 1, Name: 张三 End 一直未触发