Public CountDownLatch(int count) specifies the number of threads to pass. Public void await() makes a thread wait for public void countDown() The current thread is ready to execute. Usage scenario Makes a thread wait for another thread to execute

Use CountDownLatch to create an object that manages three threads and finishes with a fourth thread

Code implementation :(a mother and three children eat dumplings case) // test class:

public class countdownLatchdemo { public static void main(String[] args) { CountDownLatch countDownLatch = new CountDownLatch(3); mothercountdown mo = new mothercountdown(countDownLatch); mo.start(); child1 c1 = new child1(countDownLatch); C1. Elegantly-named setName (" Ming "); child2 c2 = new child2(countDownLatch); C2. Elegantly-named setName (" xiao gang "); child3 c3 = new child3(countDownLatch); C3. Elegantly-named setName (" little red "); c1.start(); c2.start(); c3.start(); }}Copy the code

// Mother class:

public class mothercountdown extends Thread{ private CountDownLatch countDownLatch; public mothercountdown(CountDownLatch countDownLatch) { this.countDownLatch=countDownLatch; } @override public void run() {// Wait for the child to finish try {countdownlatch.await (); } catch (InterruptedException e) { e.printStackTrace(); } // system.out. Println (" mom, mom, mom "); }}Copy the code

// There are 3 small dolls:

public class child1 extends Thread{ private CountDownLatch countDownLatch; public child1(CountDownLatch countDownLatch) { this.countDownLatch=countDownLatch; } @Override public void run() { for (int i = 1; i <= 10; I++) {/ / eat dumplings System. Out. Println (getName () + "is eating the first" + I + "dumplings"); Countdownlatch.countdown (); countdownlatch.countdown (); }}Copy the code
public class child2 extends Thread{ private CountDownLatch countDownLatch; public child2(CountDownLatch countDownLatch) { this.countDownLatch=countDownLatch; } @Override public void run() { for (int i = 1; i <= 15; I++) {/ / eat dumplings System. Out. Println (getName () + "is eating the first" + I + "dumplings"); Countdownlatch.countdown (); countdownlatch.countdown (); }}Copy the code
public class child3 extends Thread{ private CountDownLatch countDownLatch; public child3(CountDownLatch countDownLatch) { this.countDownLatch=countDownLatch; } @Override public void run() { for (int i = 1; i <= 20; I++) {/ / eat dumplings System. Out. Println (getName () + "is eating the first" + I + "dumplings"); Countdownlatch.countdown (); countdownlatch.countdown (); }}Copy the code

Personal summary:

1. CountDownLatch(int count) : Specifies the number of write wait threads. And defines a counter.

2. Await () : Make the thread wait and wake up the waiting thread when the counter is 0

3. CountDown () : Called when the thread completes execution, which will count -1.