CountDownLatch é usado para garantir que uma tarefa aguarde outros threads antes de iniciar. Para entender sua aplicação consideremos um servidor onde a tarefa principal só pode ser iniciada quando todos os serviços necessários forem iniciados. Funcionamento do CountDownLatch: Quando criamos um objeto de CountDownLatch, especificamos o número de threads que ele deve esperar para que todos esses threads sejam obrigados a fazer a contagem regressiva, chamando CountDownLatch.countDown() assim que estiverem concluídos ou prontos para o trabalho. Assim que a contagem chegar a zero, a tarefa em espera começará a ser executada. Exemplo de CountDownLatch em JAVA: Java // Java Program to demonstrate how // to use CountDownLatch Its used // when a thread needs to wait for other // threads before starting its work. import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String args[]) throws InterruptedException { // Let us create task that is going to // wait for four threads before it starts CountDownLatch latch = new CountDownLatch(4); // Let us create four worker // threads and start them. Worker first = new Worker(1000 latch 'WORKER-1'); Worker second = new Worker(2000 latch 'WORKER-2'); Worker third = new Worker(3000 latch 'WORKER-3'); Worker fourth = new Worker(4000 latch 'WORKER-4'); first.start(); second.start(); third.start(); fourth.start(); // The main task waits for four threads latch.await(); // Main thread has started System.out.println(Thread.currentThread().getName() + ' has finished'); } } // A class to represent threads for which // the main thread waits. class Worker extends Thread { private int delay; private CountDownLatch latch; public Worker(int delay CountDownLatch latch String name) { super(name); this.delay = delay; this.latch = latch; } @Override public void run() { try { Thread.sleep(delay); latch.countDown(); System.out.println(Thread.currentThread().getName() + ' finished'); } catch (InterruptedException e) { e.printStackTrace(); } } } Saída: WORKER-1 finished WORKER-2 finished WORKER-3 finished WORKER-4 finished main has finished
Fatos sobre CountDownLatch: - Criar um objeto CountDownLatch passando um int para seu construtor (a contagem) é na verdade o número de partes convidadas (threads) para um evento.
- O thread que depende de outros threads para iniciar o processamento aguarda até que todos os outros threads tenham chamado a contagem regressiva. Todos os threads que estão aguardando wait() continuam juntos quando a contagem regressiva chega a zero.
- O método countDown() diminui os blocos do método count e wait() até count == 0