CountDownLatch如何在JAVA中使用

  介绍

CountDownLatch如何在JAVA中使用?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

<强>方法说明:

<代码>公共空倒计时()

递减锁存器的计数,如果计数到达零,则释放所有等待的线程。如果当前计数大于零,则将计数减少。如果新的计数为零,出于线程调度目的,将重新启用所有的等待线程。

如果当前计数等于零,则不发生任何操作。

<代码>公共布尔等待(长超时,TimeUnit unit)抛出InterruptedException

使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。如果当前计数为零,则此方法立刻返回真值。

如果当前计数大于零,则出于线程调度目的,将禁用当前线程,且在发生以下三种情况之一前,该线程将一直处于休眠状态:

由于调用倒计时()方法,计数到达零;或者其他某个线程中断当前线程,或者已超出指定的等待时间。

*如果计数到达零,则该方法返回真值。

*如果当前线程,在进入此方法时已经设置了该线程的中断状态,或者在等待时被中断,则抛出InterruptedException,并且清除当前线程的已中断状态。

*如果超出了指定的等待时间,则返回值为假的。如果该时间小于等于零,则此方法根本不会等待。

<强>参数:

超时,要等待的最长时间

单位——超时参数的时间单位。

<强>返回:

如果计数到达零,则返回正确的;如果在计数到达零之前超过了等待时间,则返回假

<强>抛出:

InterruptedException,如果当前线程在等待时被中断

<强>例子1:

主线程等待子线程执行完成在执行。

import  java.util.concurrent.CountDownLatch;   import  java.util.concurrent.ExecutorService;   import  java.util.concurrent.Executors;   ,   public  class  CountdownLatchTest1  {   ,   ,,,public  static  void  main (String [], args), {   ,,,,,,ExecutorService  service =,执行人只newFixedThreadPool (3);   ,,,,,,,final  CountDownLatch  latch =, new  CountDownLatch (3);   ,,,,,,,for  (int 小姐:=,0;,小姐:& lt;, 3;,我+ +),{   ,,,,,,,,,,Runnable  Runnable =, new  Runnable (), {   ,,,,,,,,,,,,,   ,,,,,,,,,,,,@Override   ,,,,,,,,,,,,,public  void 运行(),{   ,,,,,,,,,,,,,,,,,try  {   ,,,,,,,,,,,,,,,,,,,,系统只out.println(“子线程“,+,Thread.currentThread () . getname(), +,“开始执行“);   ,,,,,,,,,,,,,,,,,,,,线程只睡眠((长),(数学只随机(),*,10000));   ,,,,,,,,,,,,,,,,,,,,系统只out.println(“子线程“,+,Thread.currentThread () . getname(), +,“执行完成“);   ,,,,,,,,,,,,,,,,,,,,latch.countDown();,//,当前线程调用此方法,则计数减一   ,,,,,,,,,,,,,,,,},catch  (InterruptedException  e), {   ,,,,,,,,,,,,,,,,,,,,e.printStackTrace ();   ,,,,,,,,,,,,,,,,}   ,,,,,,,,,,,,,}   ,,,,,,,,,,};   ,,,,,,,,,,service.execute(可运行);   ,,,,,,}   ,,,,,,   ,,,,,,,try  {   ,,,,,,,,,,系统只out.println(“主线程“,+,Thread.currentThread () . getname(), +,“等待子线程执行完成…“,);   ,,,,,,,,,,latch.await();,//,阻塞当前线程,直到计时器的值为0   ,,,,,,,,,,系统只out.println(“主线程“,+,Thread.currentThread () . getname(), +,“开始执行…“);   ,,,,,,},catch  (InterruptedException  e), {   ,,,,,,,,,,e.printStackTrace ();   ,,,,,,}   ,,,}   }

<>强例子2:

百米赛跑,4名运动员选手到达场地等待裁判口令,裁判一声口令,选手听到后同时起跑,当所有选手到达终点,裁判进行汇总汇总排名。

import  java.util.concurrent.CountDownLatch;   import  java.util.concurrent.ExecutorService;   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null   null

CountDownLatch如何在JAVA中使用