PriorityBlockingQueue是一个带优先级的阻塞队列,提供了阻塞获取操作。元素按优先级顺序被移除,该队列也没有上限(看了一下源码,PriorityBlockingQueue是对 PriorityQueue的再次包装,是基于堆数据结构的,而PriorityQueue是没有容量限制的,与ArrayList一样,所以在优先阻塞队列上put时是不会受阻的。虽然此队列逻辑上是无界的,但是由于资源被耗尽,所以试图执行添加操作可能会导致 OutOfMemoryError),但是如果队列为空,那么取元素的操作take就会阻塞,所以它的检索操作take是受阻的。另外,往入该队列中的元素要具有比较能力,插入不可比较的对象会抛出 ClassCastException。
iterator() 方法中提供的迭代器并不 保证以特定的顺序遍历 PriorityBlockingQueue 的元素。如果需要有序地进行遍历,则应使用 Arrays.sort(pq.toArray())。此外,可以使用方法 drainTo 按优先级顺序移除全部或部分元素,并将它们放在另一个 collection 中。
package entity;public class People {private Boolean isVIP; //会员private String name;public People(Boolean isVIP, String name) {super();this.isVIP = isVIP;this.name = name;}public Boolean getIsVIP() {return isVIP;}public void setIsVIP(Boolean isVIP) {this.isVIP = isVIP;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "People [isVIP=" + isVIP + ", name=" + name + "]";}
}
// Priority Queue 优先级队列@Testpublic void testListPriorityQueue(){People p3 = new People(true,"zjh");People p4 = new People(false,"zy");People p5 = new People(true,"zj");People p6 = new People(false,"zkn");People p7 = new People(true,"zyy");People p8 = new People(false,"znn");People p9 = new People(true,"js");Comparator<People> parator = (p1,p2)->{if(p1.getIsVIP() == true && p2.getIsVIP() == false){return -1;}else if (p1.getIsVIP() == false && p2.getIsVIP() == true){return 1;}else{return 0;}};PriorityBlockingQueue<People> queue = new PriorityBlockingQueue(20,parator);queue.add(p3);queue.add(p4);queue.add(p5);queue.add(p6);queue.add(p7);queue.add(p8);queue.add(p9);/*while(queue.size()>0){System.out.println(queue.remove());}*/List<People> list = new ArrayList<>();// 按顺序移除全部元素,并将元素添加到ArrayList中//queue.drainTo(list);// 按顺序移除3个元素,并将元素添加到ArrayList中queue.drainTo(list,3);list.stream().forEach(System.out::println);}
原文链接:https://blog.csdn.net/qq360694660/article/details/80270875