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;
// }
}
分享到:
相关推荐
oracle的逻辑比较和优先级规则,入门级的资料
基于优先级的防火墙规则匹配优化研究,熊俊涛,孙宝霞,针对防火墙包过滤规则的冗余问题,提出了一种规则优化处理的方法,通过命中率和最新刷新率对已经优化的规则再次进行排序,从而达
fontconfig-emoji:表情符号优先级规则
css样式应用优先级实用PPT课件.pptx
路由优先级路由优先级路由优先级路由优先级路由优先级路由优先级路由优先级
详细介绍IP优先级、TOS优先级、DSCP优先级和802.1p优先级的区别
线程池提交优先级,执行优先级
操作系统——动态优先级调度算法源代码,多道系统中多进程并发执行,为了提高系统性能解决进程死锁问题,进程的优先级是动态变化的。正在执行的进程优先级会随时间降低,而挂起的进程或等待的进程的优先级会逐渐升高...
详解CSS优先级的读法,CSS优先级包含四个级别(文内选择符,ID选择符,Class选择符,元素选择符)以及各级别出现的次数。根据这四个级别出现的次数计算得到CSS的优先级。 最近看到篇对CSS优先级有比较好的解释的...
从语言优先级及优先级口诀,一共有十五个优先级
C++进程优先级调度进程优先级调度进程优先级调度C++进程优先级调度进程优先级调度进程优先级调度
最高优先级编码器 最高优先级编码器 最高优先级编码器 最高优先级编码器
则表示,整个系统中目前有6个任务在就绪表中,分别是优先级为1,5,15,16,20,31优先级的任务就绪,若数字越低优先级越高,本例中优先级为1的任务具有最高优先级,且优先级是任务的唯一标识,请设计一程序,完成: ...
优先级大小优先级大小优先级大小优先级大小优先级大小优先级大小
CSS3规范并不是独立的,它重复了CSS的部分内容,但在其基础上进行了很多的增补与修改。...本课程是《CSS3网页设计与制作》系列课程的1-5章内容,主要包含基本选择器、伪类、伪元素、优先级规则、服务器字体等知识点
C语言编写的无优先级运算问题,C语言编写的无优先级运算问题,C语言编写的无优先级运算问题
优先级数列的实现,优先级数列的实现,优先级数列的实现
描述解决线程优先级翻转的优先级继承协议实现
快速划分测试用例的优先级快速划分测试用例的优先级 快速划分测试用例的优先级快速划分测试用例的优先级