CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
主要方法
public CountDownLatch(int count);
public void countDown();
public void await() throws
构造方法参数指定了计数的次数
countDown方法,当前线程调用此方法,则计数减一
awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0
package com.study.thread.concurrent;import java.util.Random;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @author draem0507 * @TODO 学下countdownLatch * @version 0.1 * @create 2012 15:03:28 * */public class CountDownLatchTest { /** ** CountDownLatch类是一个同步计数器,构造时传入int参数, *
** 该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1, *
** 计数器大于0 时,await()方法会阻塞程序继续执行 *
*/ public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); Worker worker1 = new Worker("小明", countDownLatch); Worker worker2 = new Worker("小红", countDownLatch); Worker worker3 = new Worker("小强", countDownLatch); Boss boss = new Boss(countDownLatch); ExecutorService service = Executors.newCachedThreadPool(); service.execute(worker1); service.execute(worker2); service.execute(worker3); service.execute(boss); service.shutdown(); }}class Worker implements Runnable { private String name; private CountDownLatch countDownLatch; public void run() { doWork(); try { Thread.sleep((new Random().nextInt(10)) * 1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(name + "-->结束干活"); countDownLatch.countDown(); } public Worker(String name, CountDownLatch countDownLatch) { this.name = name; this.countDownLatch = countDownLatch; } private void doWork() { System.out.println(name + "-->正在干活"); }}class Boss implements Runnable { private CountDownLatch countDownLatch; public Boss(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } public void run() { System.out.println("老板正在等待验工"); try { countDownLatch.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("工人干活都结束,老板开始验工"); }}
结果:
小明-->正在干活小红-->正在干活老板正在等待验工小强-->正在干活小强-->结束干活小明-->结束干活小红-->结束干活工人干活都结束,老板开始验工
不一定都按上述结果呈现,但是最后一句话肯定是最后执行
参考:
http://www.iteye.com/topic/1002652