gpt4 book ai didi

java - 生产者-消费者队列能够将项目移到前面

转载 作者:行者123 更新时间:2023-12-01 06:19:21 26 4
gpt4 key购买 nike

我用Java的LinkedBlockingDeque实现了生产者-消费者模式,但我遇到了一个问题,我有时想将一个项目(已经在队列中的某个位置)移动到队列的前面,以便更快地处理它。我永远不知道哪些已经排队的项目适合移到前面。所以我希望 LinkedBlockingDeque 被替换为可以重新排序项目的东西。我有 1 个生产者和 2-4 个消费者(自定义线程实现),并且我使用 Android 平台。我怎样才能做到这一点?有些阻塞双连接链表?

最佳答案

来 self 的评论:

您可以使用remove(Object o)检索对象并将其从队列中删除,然后使用 addFirst(Object o)将其添加到队列的前面。这将产生优先考虑该对象的效果。

您使用迭代器来检查双端队列中有哪些对象。不过要非常小心ConcurrentModificationException因为如果您在一个线程中访问集合并在另一个线程中修改它,则可能会引发它们,但是如果您使用的是阻塞队列,这应该不是问题。

来自BlockingQueue Javadoc:

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

关于java - 生产者-消费者队列能够将项目移到前面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com