CountDownLatch

关于java的CountDownLatch。Latch:门闩之意。

CountDownLatch经常用来在多线程环境下,主线程协调多个子线程的步调。生活中最相似的场景就是运动员比赛,裁判员(主线程)控制比赛的开始和结束,运动员(子线程)完成自己的比赛,当且仅当所有运动员都完成比赛时,裁判员就可以下令整场比赛结束。下面转载网友针对上述场景的模拟代码,以便更好地理解CountDownLatch的使用。

import java.util.concurrent.CountDownLatch;
2  import java.util.concurrent.Executor;
3  import java.util.concurrent.ExecutorService;
4  import java.util.concurrent.Executors;
5
6  publicclass CountDownLatchDemo {
7 privatestaticfinalint PLAYER_AMOUNT =5;
8 public CountDownLatchDemo() {
10   }
11 /**
12 * @param args
13 */
14 publicstaticvoid main(String[] args) {
16 //对于每位运动员,CountDownLatch减1后即结束比赛
17 CountDownLatch begin =new CountDownLatch(1);
18 //对于整个比赛,所有运动员结束后才算结束
19 CountDownLatch end =new CountDownLatch(PLAYER_AMOUNT);
20 Player[] plays =new Player[PLAYER_AMOUNT];
21
22 for(int i=0;i<PLAYER_AMOUNT;i++)
23 plays[i] =new Player(i+1,begin,end);
24
25 //设置特定的线程池,大小为5
26 ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
27 for(Player p:plays)
28 exe.execute(p); //分配线程
29 System.out.println("Race begins!");
30 begin.countDown();//相当于裁判员下令比赛开始
31 try{
32 end.wait(); //等待end状态变为0,即为比赛结束
33 }catch (InterruptedException e) {
35 e.printStackTrace();
36 }finally{
37 System.out.println("Race ends!");
38 }
39 exe.shutdown();
40 }
41 }

接下来是Player类

1 import java.util.concurrent.CountDownLatch;
2
3
4 publicclass Player implements Runnable {
5
6 privateint id;
7 private CountDownLatch begin;
8 private CountDownLatch end;
9 public Player(int i, CountDownLatch begin, CountDownLatch end) {
11 super();
12 this.id = i;
13 this.begin = begin;
14 this.end = end;
15 }
16
17 @Override
18 publicvoid run() {
20 try{
21 begin.await(); //等待begin的状态为0,相当于运动员已做好准备,等待裁判员宣布比赛开始。
22 Thread.sleep((long)(Math.random()*100)); //随机分配时间,即运动员完成时间
23 System.out.println("Play"+id+" arrived.");
24 }catch (InterruptedException e) {
26 e.printStackTrace();
27 }finally{
28 end.countDown(); //使end状态减1,最终减至0
29 }
30 }
31 }

posted on 2011-11-03 20:16  wenfeng762  阅读(368)  评论(0编辑  收藏  举报