SeouliteLab

Java에서 CountDownLatch를 활용한 동기화 작업 처리 방법 본문

프로그래밍

Java에서 CountDownLatch를 활용한 동기화 작업 처리 방법

Seoulite Lab 2024. 3. 26. 14:04

소개:
Java에서 CountDownLatch는 여러 스레드 간의 동기화 작업을 간편하게 처리할 수 있는 도구입니다. 이 글에서는 CountDownLatch를 사용하여 스레드 간의 작업을 동기화하는 방법에 대해 알아보겠습니다.

CountDownLatch 소개:
CountDownLatch는 java.util.concurrent 패키지에 포함되어 있으며, 주로 한 스레드가 다른 스레드의 작업이 완료될 때까지 대기하고, 모든 작업이 완료된 후에 실행되어야 하는 경우에 사용됩니다.

설정:
Java 5 이상 버전에서는 CountDownLatch 클래스를 사용할 수 있습니다.

예제 1: CountDownLatch를 사용하여 동기화 작업 처리

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int numThreads = 3;
        CountDownLatch latch = new CountDownLatch(numThreads);

        // 여러 스레드가 동기화 작업을 처리하도록 함
        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(new Worker(latch));
            thread.start();
        }

        // 모든 작업이 완료될 때까지 대기
        latch.await();
        System.out.println("모든 작업 완료");
    }

    // 동기화 작업을 처리할 Worker 클래스
    static class Worker implements Runnable {
        private CountDownLatch latch;

        public Worker(CountDownLatch latch) {
            this.latch = latch;
        }

        public void run() {
            // 동기화 작업 수행
            System.out.println(Thread.currentThread().getName() + " 작업 완료");
            latch.countDown(); // 작업이 완료될 때마다 countDown
        }
    }
}

출력 결과:

Thread-0 작업 완료
Thread-1 작업 완료
Thread-2 작업 완료
모든 작업 완료

CountDownLatch 설명:
위 예제에서는 CountDownLatch를 사용하여 여러 스레드가 동기화 작업을 처리하는 방법을 보여줍니다. CountDownLatch는 작업이 완료될 때마다 countDown() 메서드를 호출하여 내부 카운트를 감소시키고, await() 메서드를 사용하여 모든 작업이 완료될 때까지 대기합니다.