PriorityBlockingQueue优先级规则

PriorityBlockingQueue里面存储的对象必须是实现Comparable接口。队列通过这个接口的compare方法确定对象的priority。

规则是:当前和其他对象比较,如果compare方法返回负数,那么在队列里面的优先级就比较搞。

下面的测试可以说明这个断言:

查看打印结果,比较take出来的Entity和left的entity,比较他们的priority

public class TestPriorityQueue {
	
	static Random r=new Random(47);
	
	public static void main(String args[]){
		final PriorityBlockingQueue q=new PriorityBlockingQueue();
		ExecutorService se=Executors.newCachedThreadPool();
		//execute producer
		se.execute(new Runnable(){
			public void run() {
				int i=0;
				while(true){
					q.put(new PriorityEntity(r.nextInt(10),i++));
					try {
						TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		
		//execute consumer
		se.execute(new Runnable(){
			public void run() {
				while(true){
					try {
						out.println("take-- "+q.take()+" left:-- ["+q.toString()+"]");
						try {
							TimeUnit.MILLISECONDS.sleep(r.nextInt(1000));
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		try {
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.println("shutdown");
	}

}

class PriorityEntity implements Comparable<PriorityEntity> {
	private static int count=0;
	private int id=count++;
	private int priority;
	private int index=0;

	public PriorityEntity(int _priority,int _index) {
		this.priority = _priority;
		this.index=_index;
	}
	
	public String toString(){
		return id+"# [index="+index+" priority="+priority+"]";
	}

	//数字小,优先级高
	public int compareTo(PriorityEntity o) {
		return this.priority > o.priority ? 1
				: this.priority < o.priority ? -1 : 0;
	}

	//数字大,优先级高
//	public int compareTo(PriorityTask o) {
//		return this.priority < o.priority ? 1
//				: this.priority > o.priority ? -1 : 0;
//	}
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值