我有一個容量爲1的BlockingQueue。它存儲收到的股票的最後價格。價格停留在隊列中,直到客戶端輪詢隊列。然後我有一個名爲getLatestPrice()
的方法,它應該返回股票的最新價格。我的問題是,如果客戶尚未輪詢它,最新價格可能不在隊列中。它可能處於阻塞的線程中。如果被封鎖,返回最新價格是我最好的解決方案?謝謝。線程在BlockingQueue中被阻止
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
但它不是,雖然我知道有存儲在隊列中的值返回的任何值。
爲什麼你使用阻塞隊列?線程是否應該更新價格? – Basilevs