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

2020-11-24 16:54

阅读:766

标签:线程   异步   多线程   

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


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 


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

标签:线程   异步   多线程   

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


评论


亲,登录后才可以留言!