【问题标题】:Threads blocked in BlockingQueueBlockingQueue 中阻塞的线程
【发布时间】: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


【解决方案1】:

使 AtomicReference 保持最新的值,它不会阻塞更新。

【讨论】:

    【解决方案2】:

    添加另一个 BlockingQueue,使 newPrice() 在 put() 之前替换(清除/添加)此队列中的值。让 getNewPrice() 轮询这个队列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-16
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-05
      相关资源
      最近更新 更多