CountDownLatch는 작업이 시작되기 전에 다른 스레드를 기다리는지 확인하는 데 사용됩니다. 애플리케이션을 이해하기 위해 필요한 모든 서비스가 시작된 경우에만 기본 작업이 시작될 수 있는 서버를 고려해 보겠습니다. CountDownLatch 작동: CountDownLatch 객체를 생성할 때 작업이 완료되거나 준비되면 CountDownLatch.countDown()을 호출하여 모든 스레드가 카운트다운을 수행할 때까지 기다려야 하는 스레드 수를 지정합니다. 카운트가 0에 도달하자마자 대기 작업이 실행되기 시작합니다. JAVA의 CountDownLatch 예: 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(); } } } 산출: WORKER-1 finished WORKER-2 finished WORKER-3 finished WORKER-4 finished main has finished
CountDownLatch에 대한 사실: - int를 생성자(개수)에 전달하여 CountDownLatch 객체를 생성하는 것은 실제로 이벤트에 대해 초대된 당사자(스레드)의 수입니다.
- 처리를 시작하기 위해 다른 스레드에 의존하는 스레드는 다른 모든 스레드가 카운트다운을 호출할 때까지 기다립니다. 카운트다운이 0에 도달하면 wait()를 기다리고 있는 모든 스레드가 함께 진행됩니다.
- countDown() 메소드는 count == 0이 될 때까지 count 및 wait() 메소드 블록을 감소시킵니다.