【发布时间】:2014-02-08 07:34:44
【问题描述】:
我有一个容量为 1 的 BlockingQueue。它存储收到的股票的最后价格。价格一直在队列中,直到客户端轮询队列。然后我有一个名为getLatestPrice() 的方法,它应该返回股票的最新价格。我的问题是,如果客户尚未轮询最新价格,则可能不在队列中。它可能在一个阻塞的线程中。如果它被阻止,我返回最新价格的最佳解决方案是什么?谢谢。
private final BlockingQueue<PriceUpdate> latest;
private final long pollTimeout = 2;
private TimeUnit pollTimeUnit = TimeUnit.SECONDS;
public SaveListener(int capacity) {
latest = new ArrayBlockingQueue<PriceUpdate>(capacity, true);
}
public void newPrice(PriceUpdate priceUpdate) {
try {
latest.put(priceUpdate);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public PriceUpdate getNewPrice() {
try {
return latest.poll(pollTimeout, pollTimeUnit); }
catch (InterruptedException e) {
return null;
}
}
getLatestPrice() 调用getNewPrice 但是它没有返回任何值,尽管我知道队列中存储了一个值。
【问题讨论】:
-
为什么要使用阻塞队列?是否应该阻止更新价格的线程?
标签: java multithreading blockingqueue