자바 병렬 프로그래밍의 폐쇄를 실례로 설명하다
장면 적용:
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.