码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2014-04-29 13:23:21      阅读:412      评论:0      收藏:0      [点我收藏+]

标签:线程   异步   多线程   

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


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() { ... }  
  }
}





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

标签:线程   异步   多线程   

原文地址:http://blog.csdn.net/vic_fang/article/details/24653477

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!