Java还要再学一遍基础(十六)- DelayQueue使用

概述

 DelayQueue<E extends Delayed>
Delayed 元素的一个无界阻塞队列,只有在延迟期满时才能从中提取元素。该队列的 头部 是延迟期满后保存时间最长的 Delayed 元素。如果延迟都还没有期满,则队列没有头部,并且 poll 将返回 null。当一个元素的 getDelay(TimeUnit.NANOSECONDS) 方法返回一个小于等于 0 的值时,将发生到期。即使无法使用 takepoll 移除未到期的元素,也不会将这些元素作为正常元素对待。
DelayQueue继承自AbstractQueue,实现了BlockingQueue接口,内部维护了一个PriorityQueue的优先级队列,其中优先级的判定是由过期时间来决定的。这也就完成了延时队列的功能。
因此DelayQueue很适合用来做缓存,Session等类似的功能。

使用

使用DelayQueue的时候put的参数element必须是Delayed接口的子类。
public interface Delayed extends Comparable<Delayed> {
    long getDelay(TimeUnit unit);
}
getDelay方法返回与此对象相关的剩余延迟时间,以给定的时间单位表示。
同时还需要实现compareTo方法用于优先级队列的比较工作。

下面的程序简单的演示了每隔一秒到期一个元素并输出message。
public class DelayQueueDemo {

	public static void main(String[] args) throws InterruptedException {

		DelayQueue<DelayedNode> delayQueue = new DelayQueue<>();
		
		final long start = System.nanoTime();
		
		for (int i = 1; i <= 10; i++) {
			delayQueue.put(new DelayedNode(i + "", i, TimeUnit.SECONDS));
		}
		
		while (!delayQueue.isEmpty()) {
			DelayedNode node = delayQueue.take();
			System.out.println(node.getMessage() + "----> at " + (System.nanoTime() - start) / 1000 / 1000);
		}
	}

	static class DelayedNode implements Delayed {

		private final long expire;
		
		private final TimeUnit unit;
		
		private final String message;
		
		DelayedNode(String msg, int delay, TimeUnit timeUnit) {
			this.expire = System.nanoTime() + timeUnit.toNanos(delay);
			this.unit = timeUnit;
			this.message = msg;
		}
		
		@Override
		public int compareTo(Delayed o) {
			return this.getDelay(unit) > o.getDelay(unit) ? 
					1 : (this.getDelay(unit) == o.getDelay(unit) ? 0 : -1);
		}

		@Override
		public long getDelay(TimeUnit unit) {
			 
			return unit.convert(expire - System.nanoTime(), TimeUnit.NANOSECONDS);
		}
		
		public String getMessage() {
			return message;
		}
		
	}
}
输出:
1----> at 1005
2----> at 2007
3----> at 3016
4----> at 4011
5----> at 5016
6----> at 6016
7----> at 7017
8----> at 8004
9----> at 9004
10----> at 10013

注意:DelayQueue的size方法返回的个数同时包含了到期和未到期的个数。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值