DelayQueue

package collections;

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

/**
 * 测试 DelayQueueTest
 * User: zhangyong
 * Date: 13-12-3
 * Time: 下午10:29
 * To change this template use File | Settings | File Templates.
 */
public class DelayQueueTest {

    public static class DelayItem implements Delayed {

        private final long time;

        private final String name;

        public DelayItem(String name, long timeout) {
            this.name = name;
            this.time = System.currentTimeMillis() + timeout;
        }

        public String getName() {
            return name;
        }

        public long getDelay(TimeUnit unit) {
            long d = unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
            return d;
        }

        public int compareTo(Delayed other) {
            DelayItem item = (DelayItem) other;
            if (this.time > item.time) {
                return 1;
            } else {
                return -1;
            }
        }

    }

    public static void main(String[] args) {
        DelayQueue delayQueue = new DelayQueue();
        DelayItem item3 = new DelayItem("30", 30 * 1000);
        DelayItem item2 = new DelayItem("20s", 20 * 1000);
        DelayItem item1 = new DelayItem("5s", 5 * 1000);

        delayQueue.put(item3);
        delayQueue.put(item2);
        delayQueue.put(item1);

        long startTime = System.currentTimeMillis();
        for (; ; ) {
            try {
                DelayItem item = (DelayItem) delayQueue.take();
                System.out.println(item.getName() + " 耗时:" + (System.currentTimeMillis() - startTime));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}



你可能感兴趣的:(DelayQueue)