有一种情况是,我希望在BlockingQueue上使用一种方法BlockingQueue。我把这个方法描述为
检索但不移除队列的头,必要时等待元素可用。
在BlockingQueue,LinkedBlockingQueue上,我看不到相应的方法。这是存在的还是我可以这样做?我考虑过执行poll() + addFirst(),但是队列可能会在中间填满,使我陷入困境。
发布于 2011-07-25 11:36:01
将对BlockingQueue#peek()的调用包装在一个Callable中,执行它并等待Future<T>.get(long, TimeUnit)
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");
}https://stackoverflow.com/questions/6815204
复制相似问题