欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

Java中CountDownLatch用法解析

时间:2021-11-21 10:51:24|栏目:JAVA代码|点击:

CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0 时,await()方法会阻塞程序继续执行

CountDownLatch如其所写,是一个倒计数的锁存器,当计数减至0时触发特定的事件。利用这种特性,可以让主线程等待子线程的结束。下面以一个模拟运动员比赛的例子加以说明。

 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executor;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 
 public class CountDownLatchDemo {
   private static final int PLAYER_AMOUNT = 5;
   public CountDownLatchDemo() {
     // TODO Auto-generated constructor stub  
   }
   /**
   * @param args
   */
   public static void main(String[] args) {
     // TODO Auto-generated method stub
     //对于每位运动员,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) {
       // TODO: handle exception
       e.printStackTrace();
     }finally{
       System.out.println("Race ends!");
     }
     exe.shutdown();
   }
 }

接下来是Player类

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) {
     // TODO Auto-generated constructor stub
     super();
     this.id = i;
     this.begin = begin;
     this.end = end;
   }
 
   @Override
   public void run() {
     // TODO Auto-generated method stub
     try{
       begin.await();    //等待begin的状态为0
       Thread.sleep((long)(Math.random()*100));  //随机分配时间,即运动员完成时间
       System.out.println("Play"+id+" arrived.");
     }catch (InterruptedException e) {
       // TODO: handle exception
       e.printStackTrace();
     }finally{
       end.countDown();  //使end状态减1,最终减至0
     }
   }
 }

上一篇:Java日常练习题,每天进步一点点(52)

栏    目:JAVA代码

下一篇:深入浅出理解Java泛型的使用

本文标题:Java中CountDownLatch用法解析

本文地址:http://www.codeinn.net/misctech/184352.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有