Java中CountDownLatch用法解析
CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0时,await()方法会阻塞程序继续执行
CountDownLatch如其所写,是一个倒计数的锁存器,当计数减至0时触发特定的事件。利用这种特性,可以让主线程等待子线程的结束。下面以一个模拟运动员比赛的例子加以说明。
importjava.util.concurrent.CountDownLatch; importjava.util.concurrent.Executor; importjava.util.concurrent.ExecutorService; importjava.util.concurrent.Executors; publicclassCountDownLatchDemo{ privatestaticfinalintPLAYER_AMOUNT=5; publicCountDownLatchDemo(){ //TODOAuto-generatedconstructorstub } /** *@paramargs */ publicstaticvoidmain(String[]args){ //TODOAuto-generatedmethodstub //对于每位运动员,CountDownLatch减1后即结束比赛 CountDownLatchbegin=newCountDownLatch(1); //对于整个比赛,所有运动员结束后才算结束 CountDownLatchend=newCountDownLatch(PLAYER_AMOUNT); Player[]plays=newPlayer[PLAYER_AMOUNT]; for(inti=0;i<PLAYER_AMOUNT;i++) plays[i]=newPlayer(i+1,begin,end); //设置特定的线程池,大小为5 ExecutorServiceexe=Executors.newFixedThreadPool(PLAYER_AMOUNT); for(Playerp:plays) exe.execute(p);//分配线程 System.out.println("Racebegins!"); begin.countDown(); try{ end.await();//等待end状态变为0,即为比赛结束 }catch(InterruptedExceptione){ //TODO:handleexception e.printStackTrace(); }finally{ System.out.println("Raceends!"); } exe.shutdown(); } }
接下来是Player类
importjava.util.concurrent.CountDownLatch; publicclassPlayerimplementsRunnable{ privateintid; privateCountDownLatchbegin; privateCountDownLatchend; publicPlayer(inti,CountDownLatchbegin,CountDownLatchend){ //TODOAuto-generatedconstructorstub super(); this.id=i; this.begin=begin; this.end=end; } @Override publicvoidrun(){ //TODOAuto-generatedmethodstub try{ begin.await();//等待begin的状态为0 Thread.sleep((long)(Math.random()*100));//随机分配时间,即运动员完成时间 System.out.println("Play"+id+"arrived."); }catch(InterruptedExceptione){ //TODO:handleexception e.printStackTrace(); }finally{ end.countDown();//使end状态减1,最终减至0 } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。