2017-01-31 1 views
0

에 비동기 인터페이스를 변환 :Java8 - 나는 <code>Sensor</code> 인터페이스를 받아 정기적으로 결과를 전송하는 <code>Monitor</code> 클래스 정의 외부 lib 디렉토리 함께 일하고 동기 하나

public interface Sensor { 
    // called by the monitor when new results are available 
    void updatedResult(double result); 

    // called when done sending results 
    void done(); 
} 

내가 센서로 구현 한을

public class SensorImpl implements Sensor { 
    private boolean isDone; 
    private List<double> data; 

    public SensorImpl() { 
     this.isDone = false; 
     this.data = new ArrayList<>(); 
    } 

    @Override 
    void updatedResult(double result); 
     this.data.add(result); 
    } 

    @Override 
    void done() { 
     this.isDone = true; 
    } 

    public boolean isDoneReceiving() { 
     return this.isDone; 
    } 

    public List<double> getData() { 
     return this.data; 
    } 
} 

을 그리고 (간체)이 같은 내 프로그램을 실행하고 있습니다 : 다음

public void run() { 

    // initialize a sensor instance 
    SensorImpl sensor = new SensorImpl(); 

    // initialize a monitor that streams data into the sensor (async) 
    Monitor monitor = new Monitor(sensor); 

    // start monitoring the sensor 
    monitor.start(); 

    // block until done 
    while (!sensor.isDoneReceiving()) { 
     Thread.sleep(50); 
    } 

    // retrieve data and continue processing... 
    List<double> data = sensor.getData(); 

    // ... 
} 

이 기능이 작동하는 동안 sleep이있는 스레드에서 차단되는 것이 느껴지고이 클리너를 만드는 방법을 찾고 있습니다. 다양한 유형의 여러 센서를 병렬로 모니터링하기 위해 실행 프로그램을 적용 할 때 더욱 중요합니다. 어떤 도움을 주시면 감사하겠습니다.

UPDATE :

내가 나를 단순히 모든 결과를 사용할 수있을 때까지 차단 List<Double> results = sensor.get();를 호출 할 수있는 Future<List<Double>>을 구현 끝났다. 여기

public class SensorImpl implements Sensor { 

    // ... 
    private CountDownLatch countDownLatch; 

    public SensorImpl() { 
     this.countDownLatch = new CountDownLatch(1); 
    } 

    // ... 

    @Override 
    public void done() { 
     // when called by async processes, decrement the latch (and release it) 
     this.countDownLatch.countDown(); 
    } 

    // ... 

} 

가 좋은 참고가 제공 훌륭한 대답 : 귀하의 경우에는 https://stackoverflow.com/a/2180534/187907

+2

를 확인하여'done' 구현은'1의'CountDownLatch'이 같은'CountDownLatch를에'isDoneReceiving' 구현'await'을 확인 countDown' '. –

답변

1

을의 concurrent 패키지에서 여러 클래스는 어디 것, 같은 Semaphore, CoundDownLatch, CyclicBarrier 심지어 BlockingQueue을 당신을 도울 수 큐에 블록을 만들고 완료되면 다른 스레드가 값을 넣길 기다립니다.

CountDownLatch는 특정 예제에 가장 적합 할 수 있습니다. 아마도 당신이 this question을 볼 수 있습니다, 그것은 세마포와 해, CountDownLatch에 대한 좋은 개요가 있습니다

관련 문제