DelayQueue初学

初学DelayQueue, DelayQueue是一个非常好用的延时队列。
DelayQueue必须要有实现Delayed的对象参数,才能正确执行。
关于delayQueue.offer(new DelayTest(20),20,TimeUnit.MILLISECONDS);方法 ,在源码中直接调用的还是offer(E e),所以推荐使用offer(E e)方法。
源码:
public boolean offer(E e, long timeout, TimeUnit unit) {
return offer(e);
}

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueTest {

public static void main(String[] args) {
    DelayQueue delayQueue = new DelayQueue();
    delayQueue.offer(new DelayTest(10));
    delayQueue.offer(new DelayTest(5));
    delayQueue.offer(new DelayTest(1));
    delayQueue.offer(new DelayTest(15));
    delayQueue.offer(new DelayTest(19));

// 单个循环遍历
// for (int i=0; i<20; i++){
// DelayTest poll = delayQueue.poll();
// System.out.println(“queue size:”+delayQueue.size()+”,poll:”+poll);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }

    //将可以取出来的元素一次性放入集合中
    List list = new ArrayList();
    while (true) {
        int i1 = delayQueue.drainTo(list);
        System.out.println("queue size:" + delayQueue.size() +",poll size:"+list.size()+ ",poll:" + list);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

}

class DelayTest implements Delayed {

private long time;

public DelayTest(long time) {
    this.time = System.currentTimeMillis() + time * 1000;
}

//元素的获取时间,到时间才能获取 ,返回值为正,取出为null,取出为<=0,则可以取出元素
public long getDelay(TimeUnit unit) {
    return time - System.currentTimeMillis();
}

//取出元素的排列顺序,返回为<=0,则返回值与存放的时间常量无关,>0则按照存放时间的长短获取,短时间的先获得
public int compareTo(Delayed o) {
    return (int) (getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
}

}

你可能感兴趣的:(DelayQueue初学)