多线程编程--异步转同步之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() { ... } } }