CountDownLatch
来源:互联网 发布:好莱坞电影推荐 知乎 编辑:程序博客网 时间:2024/06/05 22:43
CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞程序继续执行
CountDownLatch如其所写,是一个倒计数的锁存器,当计数减至0时触发特定的事件。利用这种特性,可以让主线程等待子线程的结束。下面以一个模拟运动员比赛的例子加以说明。
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 static void main(String[] args) { //对于每位运动员,CountDownLatch减1后即结束比赛 CountDownLatch begin = new CountDownLatch(1); //对于整个比赛,所有运动员结束后才算结束 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,begin,end); //设置特定的线程池,大小为5 ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT); for(Player p:plays) exe.execute(p); //分配线程 System.out.println("Race begins!"); begin.countDown(); try{ end.await(); //等待end状态变为0,即为比赛结束 }catch (InterruptedException e) { e.printStackTrace(); }finally{ System.out.println("Race ends!"); } exe.shutdown(); } }
import java.util.concurrent.CountDownLatch; public class Player implements Runnable { private int id; private CountDownLatch begin; private CountDownLatch end; public Player(int i, CountDownLatch begin, CountDownLatch end) { super(); this.id = i; this.begin = begin; this.end = end; } public void run() { try{ begin.await(); //等待begin的状态为0 Thread.sleep((long)(Math.random()*100)); //随机分配时间,即运动员完成时间 System.out.println("Play"+id+" arrived."); }catch (InterruptedException e) { e.printStackTrace(); }finally{ end.countDown(); //使end状态减1,最终减至0 } } }
1 0
- CountDownLatch
- CountDownLatch
- CountDownLatch
- Countdownlatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch
- CountDownLatch,
- CountDownLatch
- PAT1047编程团体赛(20)
- mirantis openstack安装后处理
- [Java]简易使用JavaDoc生成说明文档
- iOS开发笔记--先弄清楚这里的学问,再来谈iOS内存管理与优化(一)
- Ubuntu下Code::Blocks无法编译/bin/sh:1:g++ not
- CountDownLatch
- No Interfaces Available In Wireshark Mac OS X
- Android屏幕适配全攻略1-从dp、sp、px说起
- c++ MFC 可改变时区的模拟时钟
- runtime基础教程(2)-OC的消息传递
- Request processing failed; nested exception is org.apache.ibatis.binding.BindingException:
- 经典洗牌算法(Knuth-Durstenfeld Shuffle)
- 文件IO,多线程,线程同步
- ICMP协议的作用是什么?(面试问答)