1. The class is introduced
A synchronization helper class that allows one or more threads to wait until a set of operations that are being performed in other threads are complete. Initialize CountDownLatch with the given count. Because the countDown() method is called, the await method blocks until the current count reaches zero. After that, all waiting threads are released and all subsequent calls to the await are returned immediately. This happens only once — the count cannot be reset. A thread (or threads) that waits for N other threads to complete something before it can execute
2. Application scenarios
In some applications, it is necessary to wait for a condition to meet the requirements before doing the next thing; An event will also be triggered when the thread is finished, so that it can proceed to the next operation. This is when CountDownLatch can be used. The most important methods for CountDownLatch are countDown() and await(), the former mainly countDown once, the latter waiting to countDown to zero, and if zero is not reached, only blocking wait.
3. Method description
countDown
public void countDown(a)Decrement the count of the latch, and if the count reaches zero, all waiting threads are released. If the current count is greater than zero, the count is reduced. If the new count is zero, all waiting threads are re-enabled for thread scheduling purposes. If the current count is equal to zero, nothing happens. awaitpublic boolean await(long timeout, TimeUnit unit) throwsInterruptedException causes the current thread to wait until the latch counts to zero unless the thread is interrupted or the specified wait time is exceeded. If the current count is zero, this method returns immediatelytrueValue. If the current count is greater than zero, the current thread is disabled for thread scheduling purposes and will remain dormant until one of three things happens: due to a callcountDown(a)Method, the count reaches zero; Or another thread interrupts the current thread; Or the specified waiting time has been exceeded. If the count reaches zero, the method returnstrueValue. If the current thread: has its interrupt state set when entering this method; Or if it is interrupted while waiting, InterruptedException is thrown and the interrupted status of the current thread is cleared. If the specified wait time is exceeded, the return value isfalse. If the time is less than or equal to zero, the method does not wait at all. Parameter: timeout - Maximum time to wait unit-timeout Time unit of the parameter. Return: Returns if the count reaches zerotrue; Returns if the wait time is exceeded before the count reaches zerofalseThrows: InterruptedException - if the current thread is interrupted while waitingCopy the code
4. Relevant examples
public class CountDownLatchTest {
// In a simulated 100-meter race, 10 runners were ready, just waiting for the judge to give the order. When everyone reaches the finish line, the race ends.
public static void main(String[] args) throws InterruptedException {
// Start the reciprocal lock
final CountDownLatch begin = new CountDownLatch(1);
// End the reciprocal lock
final CountDownLatch end = new CountDownLatch(10);
// Ten contestants
final ExecutorService exec = Executors.newFixedThreadPool(10);
for (int index = 0; index < 10; index++) {
final int NO = index + 1;
Runnable run = new Runnable() {
public void run(a) {
try {
// If the current count is zero, this method returns immediately.
/ / wait for
begin.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("No." + NO + " arrived");
} catch (InterruptedException e) {
} finally {
// When each runner reaches the finish line, end is subtracted by oneend.countDown(); }}}; exec.submit(run); } System.out.println("Game Start");
// start the game
begin.countDown();
// Wait for end to change to 0, i.e. all runners reach the finish line
end.await();
System.out.println("Game Over"); exec.shutdown(); }}Copy the code
5. Output the result
Game Start No.9 arrived No.6 arrived No.8 arrived No.7 arrived No.10 arrived No.1 arrived No.5 arrived No.4 arrived No.2 arrived No.3 arrived Game OverCopy the code