자바 병렬 프로그래밍의 폐쇄를 실례로 설명하다

폐쇄는 한 개의 문에 해당한다. 폐쇄가 끝난 상태에 도달하기 전에 이 문은 계속 닫혀 있고 어떤 라인도 통과할 수 없으며 종료 상태에 도달해야만 이 문이 열리고 모든 라인이 통과할 수 있다.그것은 한 개 이상의 라인을 하나의 사건이 발생하기를 기다릴 수 있다.폐쇄 상태는 계수기를 포함하여 정식으로 초기화되고 정수는 기다려야 할 사건의 수를 나타낸다.countDown 방법 체감 계수기는 하나의 사건이 발생했음을 나타내고await 방법은 계수기가 0에 도달하기를 기다리며 기다리는 사건이 발생했음을 나타낸다.Count Down Latch가 강조하는 것은 한 개의 라인 (또는 여러 개) 이 다른 n개의 라인이 어떤 일을 끝낸 후에야 계속 실행될 수 있다는 것이다.
장면 적용:
10명의 선수가 경주를 준비하는데, 그들은 심판의 명령이 떨어지면 동시에 달리기 시작하고, 마지막 사람이 결승점을 통과할 때 경기가 끝난다.10개의 운동은 10개의 노선과 맞먹는다. 여기서 관건은 10개의 노선을 동시에 달리도록 제어하는 것이다. 그리고 마지막 노선이 종점에 도착하는 것을 어떻게 판단하는가이다.2개의 폐쇄, 첫 번째 폐쇄로 10개의 라인을 통제하고 심판의 명령을 기다리며 두 번째 폐쇄로 경기가 끝난다.

import java.util.concurrent.CountDownLatch;
 
class Aworker implements Runnable {
 private int num;
 private CountDownLatch begin;
 private CountDownLatch end;
 
 public Aworker(int num, final CountDownLatch begin, final CountDownLatch end) {
 this.num = num;
 this.begin = begin;
 this.end = end;
 }
 
 @Override
 public void run() {
 // TODO Auto-generated method stub
 try {
  System.out.println(num + "th people is ready");
  begin.await();  // 
 } catch (InterruptedException e) {
  e.printStackTrace();
 } finally {
  end.countDown();  // , 
  System.out.println(num + "th people arrive");
 }
 }
}
 
public class Race {
 public static void main(String[] args) {
 int num = 10;
 CountDownLatch begin = new CountDownLatch(1);
 CountDownLatch end = new CountDownLatch(num);
 
 for (int i = 1; i <= num; i++) {
  new Thread(new Aworker(i, begin, end)).start();
 }
 
 try {
  Thread.sleep((long) (Math.random() * 5000));
 } catch (InterruptedException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 } 
 System.out.println("judge say : run !");
 begin.countDown(); // 
 long startTime = System.nanoTime();
 try {
  end.await(); // 
 } catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } finally {
  long endTime = System.nanoTime();
  System.out.println("judge say : all arrived !");
  System.out.println("spend time: " + (endTime - startTime));
 }
 }
}

출력

1th people is ready
2th people is ready
4th people is ready
6th people is ready
3th people is ready
10th people is ready
8th people is ready
5th people is ready
7th people is ready
9th people is ready
judge say : run !
1th people arrive
4th people arrive
10th people arrive
5th people arrive
2th people arrive
judge say : all arrived !
9th people arrive
7th people arrive
8th people arrive
3th people arrive
6th people arrive
spend time: 970933

좋은 웹페이지 즐겨찾기