其他阻塞队列DelayQueue&PriorityBlockQueue延迟阻塞队列和优先级阻塞队列

来源:互联网 发布:华为软件研发面试题 编辑:程序博客网 时间:2024/06/04 18:09

1. DelayQueue延迟阻塞队列。

    该队列主要作用是延迟添加元素,mQueue,put(Delay),当item未达到timeout的界限时,take获取元素时候会发生阻塞,一直等到元素item达到timeout延迟发生。

   DelayQueue应用场景 

   订单超时

   session绘话超时

   支付超时

   xxx超时

2.DelayQueue实例

       由于添加到DelayQueue的item延迟10s,所以调用take方法时候需要等待10秒才可以获取到,否则一直block阻塞状态。

   DelayQueue<Task> mQueue = new DelayQueue<Task>();
//添加一个task item到DelayQueue
mQueue.put(new Task(10*1000,"data"));
//直接获取
try {
System.out.println("Queue take data waiting for...");
Task task = mQueue.take();
String strData = task.getData();
System.out.println("Queue take data succ -> " + strData);

} catch (InterruptedException e) {
e.printStackTrace();
}


   public class Task implements Delayed,Runnable{
private long delay;
private String data;

public String getData(){
return this.data;
}

public long getDelay(){
return this.delay;
}

public Task(long delay,String data){
this.delay = delay + Calendar.getInstance().getTimeInMillis();
this.data = data;
}

@Override
public int compareTo(Delayed o) {
// TODO Auto-generated method stub
return 0;
}


@Override
public long getDelay(TimeUnit unit) {
// TODO Auto-generated method stub
long r = delay - Calendar.getInstance().getTimeInMillis();
return r;
}


@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("[Task]" + " run...");
}
}


3.PriorityBlockQueue优先级阻塞队列

   优先级阻塞队列,就是添加到该队列的Item,需要权值顺序处理。权值顺序处理是通过comparator接口来实现。

   特点:priorityBlockQueue是无界队列,put(capacity)无需阻塞住

           PriorityBlockQueue底层是数组Array实现,默认大小是11,扩容策略按照原来大小1.5倍大小或者2x+2长度扩容源码如下

  JDK源码

   /**
     * Inserts the specified element into this priority queue. As the queue is
     * unbounded this method will never block.
     *
     * @param e the element to add
     * @throws ClassCastException if the specified element cannot be compared
     *         with elements currently in the priority queue according to the
     *         priority queue's ordering
     * @throws NullPointerException if the specified element is null
     */
    public void put(E e) {
        offer(e); // never need to block
    }

   //扩容策略

 /**
     * Inserts the specified element into this priority queue.
     *
     * @return {@code true} (as specified by {@link Queue#offer})
     * @throws ClassCastException if the specified element cannot be
     *         compared with elements currently in this priority queue
     *         according to the priority queue's ordering
     * @throws NullPointerException if the specified element is null
     */
    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }


   /**
     * Increases the capacity of the array.
     *
     * @param minCapacity the desired minimum capacity 
     */
    private void grow(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
int oldCapacity = queue.length;
        // Double size if small; else grow by 50%
        int newCapacity = ((oldCapacity < 64)?
                           ((oldCapacity + 1) * 2):
                           ((oldCapacity / 2) * 3));
        if (newCapacity < 0) // overflow
            newCapacity = Integer.MAX_VALUE;
        if (newCapacity < minCapacity)
            newCapacity = minCapacity;
        queue = Arrays.copyOf(queue, newCapacity);
    }



4.PriorityBlockQueue实例

  private PriorityBlockingQueue<Integer> queue;

  this.queue = new PriorityBlockingQueue<Integer>(12,mComparator);
  this.queue.add(1);
  this.queue.add(10);
  this.queue.add(20);
  this.queue.add(30);

  Thread thread = new Thread(){
@Override
public void run() {
while(true){
try {
System.out.println("get data waiting...");
Integer data = queue.take();
System.out.println("get data is -> " + data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
thread.start();


private Comparator<Integer> mComparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2-o1; //权值是逆序处理,降序排列
}

 };

  

按照优先级降序处理,所以输出结果也是按照降序顺序

输出结果:

 get data waiting...
 get data is -> 30
 get data waiting...
 get data is -> 20
 get data waiting...
 get data is -> 10
 get data waiting...
 get data is -> 1
 get data waiting...

  





   

原创粉丝点击