多线程编程--异步转同步之CountDownLatch

在日常开发中,我们经常会碰到这样的情况:一些异步请求我们需要等到接收到请求后再执行下一步动作,这时我们就需要把异步动作转为同步动作。


java中给我们提供了一个CountDownLatch类来实现这个功能。


先看下CountDownLatch的官方定义:

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

意思是:CountDownLatch是一个同步助手,它可以使一个或多个线程等待,直到一系列在其他线程中执行动作完成(这些线程才被唤醒)


具体如何使用呢?

看下这段文档:

A CountDownLatch is initialized with a givencount. Theawait() methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations ofawait() return immediately. 


A useful property of aCountDownLatch is that it doesn't require that threads callingcountDown wait for the count to reach zero before proceeding, it simply prevents any thread from proceeding past anawait() until all threads could pass. 

这句翻译出来会有偏差,大家自己体会吧


详细用例:

class Driver { // ...    
  void main() throws InterruptedException {
      CountDownLatch startSignal = new CountDownLatch(1);
      CountDownLatch doneSignal = new CountDownLatch(N);
      
      for (int i = 0; i < N; ++i) // create and start threads
        new Thread(new Worker(startSignal, doneSignal)).start();
      
      doSomethingElse();            // don't let run yet
      startSignal.countDown();      // let all threads proceed
      doSomethingElse();
      doneSignal.await();           // wait for all to finish
  }   
  class Worker implements Runnable {
    private final CountDownLatch startSignal;
    private final CountDownLatch doneSignal;
   
    Worker(CountDownLatch startSignal, CountDownLatch doneSignal) {
      this.startSignal = startSignal;
      this.doneSignal = doneSignal;
    }

    	public void run() {
      try {
        startSignal.await();
        doWork();
        doneSignal.countDown();
      } catch (InterruptedException ex) {} // return;
    }
     
    void doWork() { ... }  
  }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值