래치는 일종의 관문과 같은 형태로 동작한다.
래치가 터미널 상태에 다다르면 관문이 열리고 모든 스레드가 통과한다. 래치가 한번 터미널 상태에 다다르면 그 상태를 다시 이전 상태로 되돌릴 수 없다.
특정 자원을 확보하기 전까지 작업하지 말아야할 경우에 사용할 수 있다.
public class MyLatchTest {
public static void main(String[] args) throws InterruptedException {
final int threadNums = 5;
final CountDownLatch startGate = new CountDownLatch(1); // 시작카운트 1
final CountDownLatch endGate = new CountDownLatch(threadNums); // 종료카운트 5 (스레드개수)
for(int i = 0; i < threadNums; i++) {
new Thread(() -> {
try {
startGate.await(); // 출발선에 대기
/* 어떠한 작업 */
} catch(InterrupedException e) {
/* 오류처리 */
} finally {
endGate.countDown(); // 종료카운트 다운
}
}).start();
}
startGate.countDown(); // 출발선에 대기하던 스레드들 출발
endGate.await(); // 모두 완료될 때까지 대기
}
}