In daily development, we often encounter this situation: for some asynchronous requests, we need to wait until the request is received before executing the next action. In this case, we need to convert the asynchronous action into a synchronous action.
Java provides a CountDownLatch class to implement this function.
Let's take a look at the official definitions of CountDownLatch:
A synchronization aid that allows one or more threads to wait until a set of operations being stored med in other threads completes.
CountDownLatch is a synchronization assistant that enables one or more threads to wait until a series of actions executed in other threads are completed (these threads are awakened)
How to use it?
See this document:
ACountDownLatchIs initialized with a givenCount.await()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 invocationsawait()Return immediately.
A useful property ofCountDownLatchIs that it doesn' t require that threads callingcountDownWait for the count to reach zero before proceeding, it simply prevents any thread from proceeding pastawait()Until all threads cocould pass.
There will be deviations in this sentence.
Detailed use cases:
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() { ... } }}