A king deep as the sea, from the object is a passer-by.

Hello audience gentlemen, I am the god of war, Lu Bu word, today to give you a teaching video of Lu Bu!

Ahem, no. Hello everyone, I am Lei brother, today to give you an article CountDownLatch.

Before beginning, ask everybody a very professional technical question first: play group war most afraid of _____?

A very simple send points, if the answer is wrong, that Lei brother will criticize you, ha ha.

Some people may say: play the group war most afraid of the pig teammate, but more terrible than the pig teammate is playing the group war people are not qi ah brothers, think in the group if it is 5V2 is how a picture, heartache to dare not think 🤦🏻♀️.

## Wait until everyone is together

Brother Lei was also an experienced pesticide player before his son was born, as for the level? Don’t ask! It’s bronze. Although lei’s level is not very high, he still has a basic overview. After all, he is a bronze player who has played Dota and LOL for several years, right? Ha ha.

Pesticide is the same as other Moba games, in order to win, you have to grasp each group battle, and the key of each group battle is to wait for everyone to start the group, right? This is the same idea as CountDownLatch, so let’s see what happens.

Imagine a scenario where we need to wait for some threads to finish executing before executing the main thread. How do we do that?

Join () : join() : join() : join() : join()

``````// Create thread 1
@Override
public void run(a) {
// do something}}); t1.start();// Create thread 2
@Override
public void run(a) {
// do something}}); t2.start();// Wait for threads 1 and 2 to finish
t1.join();
t2.join();
Copy the code``````

Of course, this would work if you were using Thread to perform the task. In a real (coding) environment, however, we do not use threads to perform multitasking. Instead, we use Thread pools to perform multitasking to avoid the performance overhead of repeatedly starting and destroying threads. The implementation code is as follows:

``````// Create a pool with a fixed number of threads
executorService.submit(new Runnable() {
@Override
public void run(a) {
// do something}});2 / / task
executorService.submit(new Runnable() {
@Override
public void run(a) {
// do something}});Copy the code``````

The thread pool has no join() method, so how do you wait?

This is the time to send our general “CountDownLatch”.

I have general Pan Feng who can kill Hua Xiong… A few seconds, Pan Feng… “Death”.

Wait, director, I think the story goes like this…

## CountDownLatch use

In order to implement wait for all the thread pool perform again after the main thread of logic, I decided to use AQS (AbstractQueuedSynchronizer, abstract synchronous frame) under the famous class CountDownLatch to implement this function, the specific implementation code is as follows:

``````public static void main(String[] args) throws InterruptedException {
/ / create a CountDownLatch
CountDownLatch countDownLatch = new CountDownLatch(2);

// Create a pool with a fixed number of threads
executorService.submit(new Runnable() {
@Override
public void run(a) {
// do something
try {
// Let this task execute 1.2s
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I'm Mission one."); countDownLatch.countDown(); }});2 / / task
executorService.submit(new Runnable() {
@Override
public void run(a) {
// do something
try {
// Let this task execute 1.2s
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("I'm Mission two."); countDownLatch.countDown(); }});// Wait for the task to complete
countDownLatch.await();
System.out.println("Program execution completed ~");
}
Copy the code``````

The execution results of the above procedures are as follows:As you can see from the above results, the main thread execution waits for task 1 and task 2 to complete before executing.

## Implementation principle of CountDownLatch

CountDownLatch means “count down” and “latch” means “latch”. The overall meaning of CountDownLatch can be interpreted as an inverse latch, which seems to have a “321, open sesame” feel to it, which is exactly what CountDownLatch does.

The CountDownLatch is created by passing in an integer, and until the integer “counts” to zero, the main thread waits until all other threads have executed.

#### CountDownLatch execution process

The implementation of CountDownLatch internally creates and maintains a volatile integer counter. When the countDown() method is called, it attempts to change the integer counter to -1. When wait() is called, the current thread determines whether the integer counter is 0. If 0, execution continues; if not 0, the current thread is placed in await state until one of the threads sets the counter to 0, waking up the waiting thread in the await() method to continue execution.

## CountDownLatch common methods

``````// The thread is suspended until the count value is 0
public void await(a) throws InterruptedException {};// Similar to await(), except that the execution will continue if the count value does not reach 0 after a certain amount of time
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {};// Subtracts count by 1
public void countDown(a) {};Copy the code``````

## conclusion

Using CountDownLatch, you can wait for all tasks to complete before executing the main task. It is like waiting for all players to complete the race before announcing the ranking in a race. Of course, it is the same when we play pesticide. CountDownLatch uses a counter to wait. When CountDownLatch is created, it sets a counter greater than zero and counts down to -1 every time the count () method is called until it reaches zero. The waiting task can continue.

#### Reference & thanks

www.jianshu.com/p/128476015…

Follow the public number “Java Chinese community” to see more wonderful and interesting articles!