[关闭]
@linux1s1s 2015-11-03T17:36:52.000000Z 字数 1683 阅读 1889

Java 并发编程框架(三)

Java


这一节主要讲述CountDownLatch的用法,不废话,直接上代码
测试用例CountDownLatchDemo

  1. /**
  2. CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞程序继续执行
  3. CountDownLatch如其所写,是一个倒计数的锁存器,当计数减至0时触发特定的事件。利用这种特性,可以让主线程等待子线程的结束。下面以一个模拟运动员比赛的例子加以说明。
  4. */
  5. import java.util.concurrent.CountDownLatch;
  6. import java.util.concurrent.Executor;
  7. import java.util.concurrent.ExecutorService;
  8. import java.util.concurrent.Executors;
  9. public class CountDownLatchDemo {
  10. private static final int PLAYER_AMOUNT = 5;
  11. public CountDownLatchDemo() {
  12. }
  13. public static void main(String[] args) {
  14. //对于每位运动员,CountDownLatch减1后即结束比赛
  15. CountDownLatch begin = new CountDownLatch(1);
  16. //对于整个比赛,所有运动员结束后才算结束
  17. CountDownLatch end = new CountDownLatch(PLAYER_AMOUNT);
  18. Player[] plays = new Player[PLAYER_AMOUNT];
  19. for(int i=0;i<PLAYER_AMOUNT;i++)
  20. plays[i] = new Player(i+1,begin,end);
  21. //设置特定的线程池,大小为5
  22. ExecutorService exe = Executors.newFixedThreadPool(PLAYER_AMOUNT);
  23. for(Player p:plays)
  24. exe.execute(p); //分配线程
  25. System.out.println("Race begins!");
  26. begin.countDown();
  27. try{
  28. end.await(); //等待end状态变为0,即为比赛结束
  29. }catch (InterruptedException e) {
  30. e.printStackTrace();
  31. }finally{
  32. System.out.println("Race ends!");
  33. }
  34. exe.shutdown();
  35. }
  36. }

接下来是Player类(worker线程)

  1. import java.util.concurrent.CountDownLatch;
  2. public class Player implements Runnable {
  3. private int id;
  4. private CountDownLatch begin;
  5. private CountDownLatch end;
  6. public Player(int i, CountDownLatch begin, CountDownLatch end) {
  7. super();
  8. this.id = i;
  9. this.begin = begin;
  10. this.end = end;
  11. }
  12. @Override
  13. public void run() {
  14. try{
  15. begin.await(); //等待begin的状态为0
  16. Thread.sleep((long)(Math.random()*100)); //随机分配时间,即运动员完成时间
  17. System.out.println("Play"+id+" arrived.");
  18. }catch (InterruptedException e) {
  19. // TODO: handle exception
  20. e.printStackTrace();
  21. }finally{
  22. end.countDown(); //使end状态减1,最终减至0
  23. }
  24. }
  25. }

转载文章浅析Java中CountDownLatch用法

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注