首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BlockingQueue.peekWait()

BlockingQueue.peekWait()
EN

Stack Overflow用户
提问于 2011-07-25 11:15:28
回答 1查看 2.1K关注 0票数 4

有一种情况是,我希望在BlockingQueue上使用一种方法BlockingQueue。我把这个方法描述为

检索但不移除队列的头,必要时等待元素可用。

在BlockingQueue,LinkedBlockingQueue上,我看不到相应的方法。这是存在的还是我可以这样做?我考虑过执行poll() + addFirst(),但是队列可能会在中间填满,使我陷入困境。

EN

回答 1

Stack Overflow用户

发布于 2011-07-25 11:36:01

将对BlockingQueue#peek()的调用包装在一个Callable中,执行它并等待Future<T>.get(long, TimeUnit)

代码语言:javascript
复制
final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
ExecutorService executor = Executors.newCachedThreadPool();
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);

scheduler.schedule(new Runnable()
{
  @Override
  public void run()
  {
    String e = UUID.randomUUID().toString();
    System.out.println("adding = " + e);
    queue.add(e);
  }
}, 2, TimeUnit.SECONDS);

Callable<String> task = new Callable<String>()
{
  @Override
  public String call() throws Exception
  {
    String result = null;
    while ((result = queue.peek()) == null)
    {
      Thread.sleep(100L);
    }
    return result;
  }
};

String peeked = null;
try
{
  peeked = executor.submit(task).get(1, TimeUnit.SECONDS);
  System.out.println("this should never be printed");
  queue.poll();
}
catch (TimeoutException e)
{
  System.out.println("null: peeked = " + peeked);
  e.printStackTrace();
}

try
{
  peeked = executor.submit(task).get(2, TimeUnit.SECONDS);
  System.out.println("not null: peeked = " + peeked);
}
catch (TimeoutException e)
{
  e.printStackTrace();
  System.out.println("should not throw an exception");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6815204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档