CountDownLatch理解

CountDownLatch

CountDownLatch是在java1.5被引入的,跟它一起被引入的并发工具类还有CyclicBarrier、Semaphore、ConcurrentHashMapBlockingQueue,它们都存在于java.util.concurrent包下。CountDownLatch这个类能够使一个线程等待其他线程完成各自的工作后再执行。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后再执行。

 

方法说明:

 

public void countDown()

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

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

public boolean await(long timeout, TimeUnit unit)throws InterruptedException
    
使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断或超出了指定的等待时间。如果当前计数为零,则此方法立刻返回 true 值。

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

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

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

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

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

    
    
参数:

         timeout - 要等待的最长时间

         unit - timeout 参数的时间单位。

     返回:

         如果计数到达零,则返回 true;如果在计数到达零之前超过了等待时间,则返回 false

     抛出:

          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 = Executors. newFixedThreadPool(
3);
       
final CountDownLatch latch = new CountDownLatch(3);
       
for (int i = 0; i < 3; i++) {
            Runnable runnable =
new Runnable() {
               
@Override
               
public void run() {
                   
try {
                        System.
out.println("子线程" + Thread.currentThread().getName() + "开始执行");
                        Thread. sleep((
long) (Math. random() * 10000));
                        System.
out.println("子线程" + Thread.currentThread().getName() + "执行完成");
                       
latch.countDown(); // 当前线程调用此方法,则计数减一
                    
} catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            service.execute(runnable);
        }

       
try {
            System.
out.println("主线程" + Thread.currentThread().getName() + "等待子线程执行完成..." );
            latch.await();
// 阻塞当前线程,直到计时器的值为0
           
System. out.println("主线程" + Thread.currentThread().getName() + "开始执行...");
        }
catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

输出结果:

子线程pool-1-thread-1开始执行

主线程main等待子线程执行完成...

子线程pool-1-thread-2开始执行

子线程pool-1-thread-3开始执行

子线程pool-1-thread-3执行完成

子线程pool-1-thread-2执行完成

子线程pool-1-thread-1执行完成

主线程main开始执行...

例子2:

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

 

package countdownlauch;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class CountdownLatchTest2 {

    public static void main(String[] args) {

        ExecutorService service = Executors. newCachedThreadPool();

        final CountDownLatch cdOrder = new CountDownLatch(1);

        final CountDownLatch cdAnswer = new CountDownLatch(4);

        for (int i = 0; i < 4; i++) {

            Runnable runnable = new Runnable() {

                public void run() {

                    try {

                        System. out.println("选手" + Thread.currentThread().getName() + "正等待裁判发布口令");

                        cdOrder.await();

                        System. out.println("选手" + Thread.currentThread().getName() + "已接受裁判口令");

                        Thread. sleep((long) (Math. random() * 10000));

                        System. out.println("选手" + Thread.currentThread().getName() + "到达终点");

                        cdAnswer.countDown();

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                }

            };

            service.execute(runnable);

        }

        try {

            Thread. sleep((long) (Math. random() * 10000));

            System. out.println("裁判" + Thread.currentThread ().getName() + "即将发布口令" );

            cdOrder.countDown();

            System. out.println("裁判" + Thread.currentThread ().getName() + "已发送口令,正在等待所有选手到达终点" );

            cdAnswer.await();

            System. out.println("所有选手都到达终点" );

            System. out.println("裁判" + Thread.currentThread ().getName() + "汇总成绩排名" );

        } catch (Exception e) {

            e.printStackTrace();

        }

        service.shutdown();

    }

}

输出结果:

选手pool-1-thread-1正等待裁判发布口令

选手pool-1-thread-2正等待裁判发布口令

选手pool-1-thread-4正等待裁判发布口令

选手pool-1-thread-3正等待裁判发布口令

裁判main即将发布口令

选手pool-1-thread-1已接受裁判口令

裁判main已发送口令,正在等待所有选手到达终点

选手pool-1-thread-4已接受裁判口令

选手pool-1-thread-2已接受裁判口令

选手pool-1-thread-3已接受裁判口令

选手pool-1-thread-1到达终点

选手pool-1-thread-3到达终点

选手pool-1-thread-4到达终点

选手pool-1-thread-2到达终点

所有选手都到达终点

裁判main汇总成绩排名

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值