What does CountDownLatch do

CountDownLatch is a class in the java.util.Concurrent package that acts as a synchronizer to coordinate synchronization between multiple threads. In general, CountDownLatch allows one or more threads to stop at some point during a run and wait for other threads to complete some task before continuing.

A similar task can be done using a thread’s join() method: when the join() method of another thread is called at the wait point, the current thread waits for the join thread to finish before continuing, but the CountDownLatch implementation is simpler and has more functionality than join.

How to use CountDownLatch

The CountDownLatch constructor takes an int as a counter. For example, if you want N to finish before continuing, you pass N when creating CountDownLatch.

The thread that needs to wait calls the await method of CountDownLatch, which blocks until the count is reduced to zero, while the thread that has reached its expectation calls the CountDownLatch countDown() method, which reduces the count N by one. Since the countDown method can be called from anywhere, the counter N can represent either N threads or N execution steps of a thread. When representing multiple threads, you simply pass the reference to CountDownLatch into the thread.

When N is 1, it is reduced to a single event, that is, one thread notifies other threads. The effect is equivalent to wait and notifyAll of objects. When N is 0, calling the await method does not block the current thread.

To sum up, there are three main steps to use CountDownLatch. First, when creating the CountDownLatch instance, the counter value N is specified by the constructor. The waiting thread then calls the await method of the CountDownLatch instance, and the wait counter will have a value of 0; The waiting thread calls the countDown method of the CountDownLatch instance when the task completes, and the value of the counter decreases by one.

An example: Three threads parse data in a table, and the main thread waits until the table is parsed

public class CountDownLatchTest { public static void main(String[] args) throws Exception{ /* Create the CountDownLatch instance and initialize the counter value to 3*/ final CountDownLatch downLatch = new CountDownLatch(3); /* Create three threads and wait 1s for each thread to execute a time-consuming task */for(int i = 0; i < 3; i++){ final int num = i; new Thread(newRunnable() {
                public void run() {
                    try {
                        Thread.sleep(1000);

                    }catch (InterruptedException e){
                        e.printStackTrace();

                    }

                    System.out.println(String.format("thread %d has finished",num)); CountDownLatch () */ downlatch.countdown (); } }).start(); } /* The main thread calls the await() method and waits until the other three threads have finished executing */ downlatch.await (); System.out.print("all threads have finished,main thread will continue run"); }}Copy the code

Running results:

Three, CountDown’s deficiency

CountDownLatch is one-time. It is not possible to reinitialize or change the value of its internal counter. CountDownLatch cannot be used again after it has been used.

CyclicBarrier for Concurrent Programming in Java

Semaphore Usage Guide for Concurrent Programming in Java