CountDownLatch是一个同步辅助类,犹如倒计时计数器,创建对象时通过构造方法设置初始值,调用CountDownLatch对象的await()方法则处于等待状态,调用countDown()方法就将计数器减1,当计数到达0时,则所有等待者或单个等待者开始执行。

简单例子

import java.util.concurrent.CountDownLatch;

/**
* 出发点:等待所有线程执行完成
* @author yinchuan.chen
*
*/
public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException {
CountDownLatch cdl = new CountDownLatch(4);
for(int i = 0; i < 4; i++) {
final int count = i;
Thread t = new Thread(new Runnable() { public void run() {
System.out.println(count);
cdl.countDown();
}
}); t.start();
} cdl.await();
System.out.println("等所有现场执行完成,才打印"); }
}

注:countDown最好是在finally里面调用

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo {
private static final int PLAYER_AMOUNT = 5;
public CountDownLatchDemo() {
}
/**
* @param args
*/
public static void main(String[] args) {
//对于整个比赛,所有运动员结束后才算结束
CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
Player[] plays = new Player[PLAYER_AMOUNT]; for(int i=0;i<PLAYER_AMOUNT;i++)
plays[i] = new Player(i+1,end); //设置特定的线程池,大小为5
ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
for(Player p:plays)
exe.execute(p); //分配线程
System.out.println("Race begins!");
try{
end.await(); //等待end状态变为0,即为比赛结束
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("Race ends!");
}
exe.shutdown();
}
} class Player implements Runnable { private int id;
private CountDownLatch end;
public Player(int i, CountDownLatch end) {
super();
this.id = i;
this.end = end;
} @Override
public void run() {
try{
Thread.sleep((long)(Math.random()*100)); //随机分配时间,即运动员完成时间
System.out.println("Play"+id+" arrived.");
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
end.countDown(); //使end状态减1,最终减至0
}
}
}
参考 http://www.cnblogs.com/yezhenhan/archive/2012/01/07/2315652.html

CountDownLatch使用例子的更多相关文章

  1. CountDownLatch如何使用

    正如每个Java文档所描述的那样,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.在Java并发中,countdownlatch的概念是一 ...

  2. 什么时候使用CountDownLatch

    正如每个Java文档所描述的那样,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.在Java并发中,countdownlatch的概念是一 ...

  3. CountDownLatch使用详解

    正如每个Java文档所描述的那样,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.在Java并发中,countdownlatch的概念是一 ...

  4. CountDownLatch使用场景

    正如每个Java文档所描述的那样,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.在Java并发中,countdownlatch的概念是一 ...

  5. 并发编程(二)—— CountDownLatch、CyclicBarrier和Semaphore

    本文将讲解CountDownLatch,CyclicBarrier和Semaphore这三个并发包里面的辅助类. CountDownLatch 正如每个Java文档所描述的那样,CountDownLa ...

  6. CountDownLatch的简单讲解

    正如每个Java文档所描述的那样,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.在Java并发中,countdownlatch的概念是一 ...

  7. 深入浅出Java并发中的CountDownLatch

      1. CountDownLatch 正如每个Java文档所描述的那样,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行.在Java并发中 ...

  8. 腾讯面试居然跟我扯了半小时的CountDownLatch

    一个长头发.穿着清爽的小姐姐,拿着一个崭新的Mac笔记本向我走来,看着来势汹汹,我心想着肯定是技术大佬吧!但是我也是一个才华横溢的人,稳住我们能赢. 面试官:看你简历上有写熟悉并发编程,CountDo ...

  9. java并发编程JUC第九篇:CountDownLatch线程同步

    在之前的文章中已经为大家介绍了java并发编程的工具:BlockingQueue接口.ArrayBlockingQueue.DelayQueue.LinkedBlockingQueue.Priorit ...

随机推荐

  1. DTMF Stresstesting

    import threading,time,serial,sys from random import randrange   port_snd=14 port_recv=2 recnt=0 ser_ ...

  2. git提交

    1.git pull 本地已经commit 2.git checkout master 3.git pull 4.git checkout - 5.git merge master 6.git pus ...

  3. 3n+1问题

    猜想: 对于任意大于1的自然数n,若n为奇数,则将n变为3n+1,否则变为n的一半. 经过若干次这样的变换,一定会使n变为1.例如3->10->5->16->8->2-& ...

  4. tableview在第一次显示时会自动relodata

    tableview在第一次显示时会自动加载数据

  5. Leetcode: Guess Number Higher or Lower

    We are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to gues ...

  6. HDU 2993 MAX Average Problem(斜率优化)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2993 Problem Description Consider a simple sequence w ...

  7. zw版【转发·台湾nvp系列Delphi例程】HALCON Component Histogram

    zw版[转发·台湾nvp系列Delphi例程]HALCON Component Histogram unit Unit1;interfaceuses Windows, Messages, SysUti ...

  8. .NET 通过SmtpClient发送邮件 提示 4.7.1 service unavailable try again later 解决办法

    最近用C#的SmtpClient发送电子邮件碰到这个错误: 正在处理错误. 服务器响应为:4.7.1 Service unavailable - try again later 换了其他的SMTP服务 ...

  9. VS中快速生成json数据格式对应的实体

    JSON是一种取代XML的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度. JSON就是一串字符串 只不过元素会使用特定的符号标注. {} 双 ...

  10. Image对象及其子类BufferedImage

    (1)java.awt.Image图像类是抽象类,提供获得绘图对象.图像缩放.选择图像平滑度等功能,声明如下: public abstract class Image extends Object { ...