天天看点

多线程编程--异步转同步之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 <code>countdownlatch</code> is initialized with a givencount. the<code>await()</code> 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 of<code>await()</code> return immediately. 

a useful property of a<code>countdownlatch</code> is that it doesn‘t require that threads calling<code>countdown</code> wait for the count to reach zero before proceeding, it simply prevents

any thread from proceeding past an<code>await()</code> until all threads could pass. 

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

详细用例:

继续阅读