PriorityBlockingQueue基于优先级的阻塞队列
优先级的判断通过构造函数传入的Compator对象来决定,也就是说传
入队列的对象必须实现Comparable接口,在实现PriorityBlockingQueue
时,内部控制线程同步的锁采用的是公平锁,他也是一个无界的队列
按照自己定义的顺序进行执行队列,不是按照现后顺序进行的
PriorityBlockingQueue传的是自定义的对象,如Node类(实现了排序)
package com.bfxy.thread.core.collection;
import java.util.concurrent.PriorityBlockingQueue;
public class UsePriorityBlockingQueue {
public static void main(String[] args) throws InterruptedException {
PriorityBlockingQueue<Node> pbq = new PriorityBlockingQueue<Node>();
Node n3 = new Node(3, "node3");
Node n4 = new Node(4, "node4");
Node n2 = new Node(2, "node2");
Node n1 = new Node(1, "node1");
pbq.add(n4);
pbq.add(n3);
pbq.add(n1);
pbq.add(n2);
System.err.println("0 容器为: " + pbq);
System.err.println("1 获取元素: " + pbq.take().getId());
System.err.println("1 容器为: " + pbq);
System.err.println("2 获取元素: " + pbq.take().getId());
System.err.println("2 容器为: " + pbq);
System.err.println("3 获取元素: " + pbq.take().getId());
System.err.println("3 容器为: " + pbq);
System.err.println("4 获取元素: " + pbq.take().getId());
}
}
Node类:
package com.bfxy.thread.core.collection;
public class Node implements Comparable<Node>{
private int id;
private String name;
public Node() {
}
public Node(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Node node) {
return this.id > node.id ? 1 : (this.id < node.id ? -1 : 0);
}
public String toString() {
return this.id + ":" + this.name;
}
}
始终把优先级最高的放在第一位方便取,其他不变,因为在去的过程中可能会添加下个数据,可能是优先级高的,如果不高则取下一个优先级高的放在第一位,以此类推,二分法