PriorityBlockingQueue使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013673252/article/details/84523949

priorityBlockingQueue是一个无界队列,它没有限制,在内存允许的情况下可以无限添加元素;它又是具有优先级的队列,是通过构造函数传入的对象来判断,传入的对象必须实现comparable接口。

首先创建一个person对象,里面有id name 两个属性,person实现了comparable接口,并重写compareTo方法

public class Person implements Comparable<Person>{
	private int id;
	private String 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;
	}
	public Person(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
	public Person() {
	}
	@Override
	public String toString() {
		return this.id + ":" + this.name;
	}
	@Override
	public int compareTo(Person person) {
		return this.id > person.getId() ? 1 : ( this.id < person.getId() ? -1 :0);
	}
}

mian方法中测试 

	public static void main(String[] args) {
		PriorityBlockingQueue<Person> pbq = new PriorityBlockingQueue<>();
		pbq.add(new Person(3,"person3"));
		System.err.println("容器为:" + pbq);
		pbq.add(new Person(2,"person2"));
		System.err.println("容器为:" + pbq);
		pbq.add(new Person(1,"person1"));
		System.err.println("容器为:" + pbq);
		pbq.add(new Person(4,"person4"));
		System.err.println("容器为:" + pbq);
	}

上面代码无序的添加了4个元素,打印结果为:

对结果分析,每次添加一个元素,PriorityBlockingQueue中的person都会执行compareTo方法进行排序,但是只是把第一个元素排在首位,其他元素按照队列的一系列复杂算法排序。这就保障了每次获取到的元素都是经过排序的第一个元素。

	public static void main(String[] args) throws InterruptedException {
		PriorityBlockingQueue<Person> pbq = new PriorityBlockingQueue<>();
		pbq.add(new Person(3,"person3"));
		System.err.println("容器为:" + pbq);
		pbq.add(new Person(2,"person2"));
		System.err.println("容器为:" + pbq);
		pbq.add(new Person(1,"person1"));
		System.err.println("容器为:" + pbq);
		pbq.add(new Person(4,"person4"));
		System.err.println("容器为:" + pbq);
		System.err.println("分割线----------------------------------------------------------------" );
		
		
		System.err.println("获取元素 " + pbq.take().getId());
		System.err.println("容器为:" + pbq);
		System.err.println("分割线----------------------------------------------------------------" );
		
		System.err.println("获取元素 " + pbq.take().getId());
		System.err.println("容器为:" + pbq);
		System.err.println("分割线----------------------------------------------------------------" );
		
		System.err.println("获取元素 " + pbq.take().getId());
		System.err.println("容器为:" + pbq);
		System.err.println("分割线----------------------------------------------------------------" );
		
		System.err.println("获取元素 " + pbq.take().getId());
		System.err.println("容器为:" + pbq);
		System.err.println("分割线----------------------------------------------------------------" );
	}

 

每次获取的元素都是排序后第一个元素。

猜你喜欢

转载自blog.csdn.net/u013673252/article/details/84523949
今日推荐