问题描述
我有一个阻塞对象队列。
I have a blocking queue of objects.
我想编写一个阻塞的线程,直到队列中有一个对象为止。类似于BlockingQueue.take()提供的功能。
I want to write a thread that blocks till there is a object on the queue. Similar to the functionality provided by BlockingQueue.take().
但是,由于我不知道我是否能够成功处理对象,我想偷看()而不是删除对象。我只想在能够成功处理它的情况下删除该对象。
However, since I do not know if I will be able to process the object successfully, I want to just peek() and not remove the object. I want to remove the object only if I am able to process it successfully.
所以,我想要一个阻塞的peek()函数。目前,peek()只是在队列为空时根据javadoc返回。
So, I would like a blocking peek() function. Currently, peek() just returns if the queue is empty as per the javadocs.
我错过了什么吗?还有其他方法可以实现此功能吗?
Am I missing something? Is there another way to achieve this functionality?
编辑:
任何想法如果我只是使用线程安全队列而偷看和睡觉?
Any thoughts on if I just used a thread safe queue and peeked and slept instead?
public void run() {
while (!__exit) {
while (__queue.size() != 0) {
Object o = __queue.peek();
if (o != null) {
if (consume(o) == true) {
__queue.remove();
} else {
Thread.sleep(10000); //need to backoff (60s) and try again
}
}
}
Thread.sleep(1000); //wait 1s for object on queue
}
}
注意我只有一个消费者线程和一个(单独的)生产者线程。我想这不如使用BlockingQueue那么有效...任何评论都赞赏。
Note that I only have one consumer thread and one (separate) producer thread. I guess this isn't as efficient as using a BlockingQueue... Any comments appreciated.
推荐答案
你可以使用并从队列中物理删除该项目(使用 takeLast()
)但是如果使用 putLast(E e)处理失败,则在队列末尾再次替换它)
。同时,您的生产者会使用 putFirst(E e)
将元素添加到队列的前。
You could use a LinkedBlockingDeque and physically remove the item from the queue (using takeLast()
) but replace it again at the end of the queue if processing fails using putLast(E e)
. Meanwhile your "producers" would add elements to the front of the queue using putFirst(E e)
.
您总是可以在自己的 Queue
实现中封装此行为,并提供 blockingPeek()
方法在底层 LinkedBlockingDeque takeLast()
后跟 putLast()
/ code>。因此,从调用客户端的角度来看,元素永远不会从队列中删除。
You could always encapsulate this behaviour within your own Queue
implementation and provide a blockingPeek()
method that performs takeLast()
followed by putLast()
behind the scenes on the underlying LinkedBlockingDeque
. Hence from the calling client's perspective the element is never removed from your queue.
这篇关于java BlockingQueue没有阻塞偷看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!