欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中CountDownLatch用法解析

程序员文章站 2024-03-08 09:23:34
countdownlatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countdown()方法,计数器减1,计数器大于0 时,awai...

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
     }
   }
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。