으로는 생산자 소비자와 차단 큐를 사용할 수 있습니다
또는
당신은 당신의 문제를 해결하기 위해 자바 동시성의 카운트 다운 래치를 사용할 수 있습니다.
CountDownLatch의 작동 방식은 무엇입니까?
// 지정된 카운트로 초기화 된 CountDownLatch를를 구축 :
CountDownLatch.java 클래스는 내부에 하나의 생성자가 정의합니다.
이 수는 본질적으로 래치가 대기해야하는 스레드의 수입니다. 이 값은 한 번만 설정할 수 있으며 CountDownLatch는이 수를 재설정 할 수있는 다른 메커니즘을 제공하지 않습니다.
CountDownLatch와의 첫 번째 상호 작용은 다른 스레드를 기다리는 goind 인 주 스레드와 관련이 있습니다. 이 주 스레드는 다른 스레드를 시작한 직후에 CountDownLatch.await() 메서드를 호출해야합니다. 실행은 시간까지 await() 메서드에서 멈추고 다른 스레드는 실행을 완료합니다.
다른 N 개의 스레드는 작업을 완료 한 CountDownLatch 개체에 알릴 필요가 있기 때문에 래치 개체에 대한 참조를 가져야합니다. 이 알림은 다음 방법으로 수행됩니다. CountDownLatch.countDown(); 메소드를 호출 할 때마다 생성자에서 설정된 초기 카운트가 1 씩 감소합니다. 따라서 N 개의 모든 스레드가이 메서드를 호출하면 count가 0에 도달하고 주 스레드는 await() 메서드를지나 실행을 다시 시작할 수 있습니다.
다음은 간단한 예입니다. Decrementer이 경우에
CountDownLatch, the waiting Waiter is released from the await() call.
CountDownLatch latch = new CountDownLatch(3);
Waiter waiter = new Waiter(latch);
Decrementer decrementer = new Decrementer(latch);
new Thread(waiter) .start();
new Thread(decrementer).start();
Thread.sleep(4000);
public class Waiter implements Runnable{
CountDownLatch latch = null;
public Waiter(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Waiter Released");
}
}
public class Decrementer implements Runnable {
CountDownLatch latch = null;
public Decrementer(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
try {
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
Thread.sleep(1000);
this.latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
에 카운트 다운() 3 회 호출 한 후에는 해당 값을 전달하는 하나 개의 스레드에서 retrun 값을 얻을 필요가로 대신 실행 가능한 쓰레드를 생성하는 호출 할 수 있습니다 두 번째 스레드.
'java.util.concurrent' 패키지에서 클래스를 확인하십시오. – Stewart
아주 간단한 작업이 있다면 플래그로 작동하는'volatile' 변수 만 있으면됩니다. 좀 더 복잡한 기능이 있다면 두 스레드가 사용하는 데이터에 대해'concurrent' 변수가 필요할 것입니다. Java 라이브러리에서 동시성을 구현할 수있는 방법이 많이 있으므로 거기에서 뭔가를 선택하십시오. – razvanz