gpt4 book ai didi

Java8 - 将异步接口(interface)转换为同步接口(interface)

转载 作者:行者123 更新时间:2023-12-01 08:57:16 25 4
gpt4 key购买 nike

我正在使用定义 Monitor 的外部库接受 Sensor 的类接口(interface)并定期将结果发送到其中:

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 线程上阻塞感觉很恶心,我正在寻找一种方法来使其更干净。当应用执行器并行监控多个不同类型的传感器时,这一点变得更加重要。任何帮助将不胜感激。

更新:

我最终实现了Future<List<Double>> ,这让我可以简单地调用 List<Double> results = sensor.get(); ,它会阻塞,直到所有结果都可用。

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

最佳答案

就您的情况而言,concurrent 包中的几个类可以为您提供帮助,例如 SemaphoreCoundDownLatchCyclicBarrier code> 甚至是 BlockingQueue,您可以在其中阻塞队列并等待其他线程完成后将值放入其中。

CountDownLatch 很可能最适合您的特定示例。也许您可以查看this question ,它对 Semaphore 和 CountDownLatch 有很好的概述:

关于Java8 - 将异步接口(interface)转换为同步接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41968030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com