PriorityBlockingQueue同优先级元素不能按先后插入顺序出列
PriorityBlockingQueue是典型的堆排序,堆排序只要满足每个父节点比子节点小或大(最小堆和最大堆)就行了,当poll以后,会按堆排序算法再次整理元素队列(在这个队列里面,堆排序只有所有元素出列了才完成了排序),这可能导致同优先级元素中后插入的元素跑到前面去。
public class Bean implements Runnable, Comparable<Bean>{
private int no;
private int level;
public Bean(int no, int level) {
super();
this.no = no;
this.level = level;
}
@Override
public void run() {
}
@Override
public int compareTo(Bean o) {
if (level > o.level) {
return -1;
} else if (level < o.level) {
return 1;
}
return 0;
}
@Override
public String toString() {
return "Bean [no=" + no + ", level=" + level + "]";
}
public static void main(String[] args) {
PriorityBlockingQueue<Bean> queue = new PriorityBlockingQueue<>();
queue.add(new Bean(1, 2));
queue.add(new Bean(2, 1));
queue.add(new Bean(3, 3));
queue.add(new Bean(4, 1));
queue.add(new Bean(5, 1));
int size = queue.size();
for (int i = 0; i < size; i++) {
System.out.println(queue.poll().toString());
}
}
}
以上代码的执行结果如下:
如果是同优先级执行顺序不要求,这也不会有什么问题,但是希望按照添加顺序先后执行,那最好是用时间来区分开来,不出现等于的情况。
顺便说下,这玩意的迭代器是用遍历数组的方法遍历的,但是排序是堆排序,不用指望能按优先级遍历元素。