五 : PriorityBlockingQueue 优先级阻塞队列

来源:互联网 发布:图像算法工程师待遇 编辑:程序博客网 时间:2024/06/05 17:03


一 :优先级阻塞队列 PriorityBlockingQueue


该实现类需要自己实现一个继承了 Comparator 接口的类, 在插入资源时会按照自定义的排序规则来对资源数组进行排序。 其中值大的排在数组后面 ,取值时从数组投开始取







图中可以看出, 该实现类共有四个 , 第一个和第二个分别调用了第三个构造函数 , 如果用户有指定参数,则将指定参数值传入,如果没有,则使用默认值初始化属性。


二 : 该实现类的 put 方法





从图中可以看出 ,put方法里面调用了该类的offer方法 ,offer方法先判断传入的资源是否为空,不为空的话判断当前资源的数目是否大于数组最大的长度,如果大于的话,则增大数组的长度。 按照排序方法将资源插入数组中 。


接下来详看 数组扩增  和  按照排序条件对数组进行插入。



插入的函数可以看出 , 使用位运算符 ,每次除二,跟他前一半值进行对比,如果大于则直接存入,否则与其调换位置。


三: 该实现类的 take 方法



由上图可以看出 , 取资源的时候每次都取数组的第一个资源,并且调用后会对资源数组重新排序。 总结 , 因为插入时是将大值排在后,所以取值的时候会从小到大取 。


四 : 代码实现


public class PriorityBlockingQueue
{
static Logger logger = LogManager.getLogger();


static Random random = new Random(47);


public static void main(String args[]) throws InterruptedException
{
PriorityBlockingQueue<PriorityEntity> queue = new PriorityBlockingQueue<PriorityEntity>();
ExecutorService executor = Executors.newCachedThreadPool();


executor.execute(new Runnable()
{
public void run()
{
int i = 0;
while (true)
{
queue.put(new PriorityEntity(random.nextInt(10), i++));
try
{
TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
}
catch (InterruptedException e)
{
logger.error(e);
}
}
}
});


executor.execute(new Runnable()
{
public void run()
{
while (true)
{
try
{
System.out.println("take-- " + queue.take() + " left:-- [" + queue.toString() + "]");
try
{
TimeUnit.MILLISECONDS.sleep(random.nextInt(1000));
}
catch (InterruptedException e)
{
logger.error(e);
}
}
catch (InterruptedException e)
{
logger.error(e);
}
}
}
});


try
{
TimeUnit.SECONDS.sleep(5);
}
catch (InterruptedException e)
{
logger.error(e);
}
}


static 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)
{
System.out.println("_priority : " + _priority);
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;
}
}
}



0 0
原创粉丝点击