Java PriorityBlockingQueue的问题

qibobo 2014-12-12 03:49:19
项目中有一个生产者消费者的情形,队列用了Java 的PriorityBlockingQueue,queue中的对象代码如下:
class TestCaseEntry implements Comparable<TestCaseEntry>{

private Long tcId;
private Integer days;


public TestCaseEntry(Long tcId, Integer days) {
this.tcId = tcId;
this.days = days;
}


public int compareTo(TestCaseEntry t) {
// TODO Auto-generated method stub
return this.days-t.days;
}
public String toString()
{
return this.days.toString();
}

public Long getTcId() {
return tcId;
}


public void setTcId(Long tcId) {
this.tcId = tcId;
}


public Integer getDays() {
return days;
}


public void setDays(Integer days) {
this.days = days;
}

}
需求就是每次从queue中取出days最小的若干个TestCaseEntry的对象。今天发现一个问题,系统运行了几天之后,queue不再是取最小的那个对象了。当时queue中有3000多个对象,days有0,5,10等值,queue的第一个元素竟然是days为10的,看系统的log,通过peek方法拿到的第一个元素确实是10。写了几个测试程序都没复现这个问题,但是系统中确实好几个queue都有这个问题。各位大牛谁知道咋回事?
...全文
180 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qibobo 2014-12-15
  • 打赏
  • 举报
回复
迭代器确实不是按queue的顺序迭代的,但是其第一个元素肯定应该是queue应该取的第一个元素,现在的问题是迭代出来的第一个元素也不是最优先的那个。
miracleliu 2014-12-12
  • 打赏
  • 举报
回复
怎么从队列取的代码没贴啊
miracleliu 2014-12-12
  • 打赏
  • 举报
回复
供参考: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/PriorityBlockingQueue.html 此类及其迭代器可以实现 Collection 和 Iterator 接口的所有可选 方法。iterator() 方法中提供的迭代器并不 保证以特定的顺序遍历 PriorityBlockingQueue 的元素。如果需要有序地进行遍历,则应考虑使用 Arrays.sort(pq.toArray())。此外,可以使用方法 drainTo 按优先级顺序移除 全部或部分元素,并将它们放在另一个 collection 中。 在此类上进行的操作不保证具有同等优先级的元素的顺序。如果需要实施某一排序,那么可以定义自定义类或者比较器,比较器可使用修改键断开主优先级值之间的联系。例如,以下是应用先进先出 (first-in-first-out) 规则断开可比较元素之间联系的一个类。要使用该类,则需要插入一个新的 FIFOEntry(anEntry) 来替换普通的条目对象。 class FIFOEntry<E extends Comparable<? super E>> implements Comparable<FIFOEntry<E>> { static final AtomicLong seq = new AtomicLong(0); final long seqNum; final E entry; public FIFOEntry(E entry) { seqNum = seq.getAndIncrement(); this.entry = entry; } public E getEntry() { return entry; } public int compareTo(FIFOEntry<E> other) { int res = entry.compareTo(other.entry); if (res == 0 && other.entry != this.entry) res = (seqNum < other.seqNum ? -1 : 1); return res; } }

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧