PriorityBlockingQueue使用

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("分割线----------------------------------------------------------------" );
	}

 

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

  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值