首页 > 学院 > 开发设计 > 正文

CountDownLatch使用例子

2019-11-14 22:19:58
字体:
来源:转载
供稿:网友
CountDownLatch使用例子

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.VEVb.com/yezhenhan/archive/2012/01/07/2315652.html

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表