java中DelayQueue实例用法详解
时间:2021-03-10 09:23:33|栏目:JAVA代码|点击: 次
在阻塞队里中,除了对元素进行增加和删除外,我们可以把元素的删除做一个延迟的处理,即使用DelayQueue的方法。这里的删除需要一定的时间才能生效,有点类似于过期处理的理念。下面我们就DelayQueue的概念、特点进行讲解,然后在代码示例中体会DelayQueue的使用。
1.概念
是一个带有延迟时间的无界阻塞队列。队列中的元素,只有等延时时间到了,才能取出来。此队列一般用于过期数据的删除,或任务调度。以下,模拟一下定长时间的数据删除。
2.特点
(1)无边界设计
(2)添加(put)不阻塞,移除阻塞
(3)元素都有一个过期时间
(4)取元素只有过期的才会被取出
3.实例
每个需要放入DelayQueue队列元素需要实现Delayed接口,下面我们创建DelayObject 类,其实例对象将被放入DelayQueue中。其构造函数包括字符串类型数据及延迟毫秒变量。
public class DelayObject implements Delayed {
private String data;
private long startTime;
public DelayObject(String data, long delayInMilliseconds) {
this.data = data;
this.startTime = System.currentTimeMillis() + delayInMilliseconds;
}
DelayQueue的应用实例
package org.dromara.hmily.demo.springcloud.account.service;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* @description: 延时队列测试
* @author: hh
*/
public class DelayedQueneTest {
public static void main(String[] args) throws InterruptedException {
Item item1 = new Item("item1", 5, TimeUnit.SECONDS);
Item item2 = new Item("item2",10, TimeUnit.SECONDS);
Item item3 = new Item("item3",15, TimeUnit.SECONDS);
DelayQueue<Item> queue = new DelayQueue<>();
queue.put(item1);
queue.put(item2);
queue.put(item3);
System.out.println("begin time:" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
for (int i = 0; i < 3; i++) {
Item take = queue.take();
System.out.format("name:{%s}, time:{%s}\n",take.name, LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
}
}
}
class Item implements Delayed{
/* 触发时间*/
private long time;
String name;
public Item(String name, long time, TimeUnit unit) {
this.name = name;
this.time = System.currentTimeMillis() + (time > 0? unit.toMillis(time): 0);
}
@Override
public long getDelay(TimeUnit unit) {
return time - System.currentTimeMillis();
}
@Override
public int compareTo(Delayed o) {
Item item = (Item) o;
long diff = this.time - item.time;
if (diff <= 0) {// 改成>=会造成问题
return -1;
}else {
return 1;
}
}
@Override
public String toString() {
return "Item{" +
"time=" + time +
", name='" + name + '\'' +
'}';
}
}
运行结果:每5秒取出一个
begin time:2019-05-31T11:58:24.445
name:{item1}, time:{2019-05-31T11:58:29.262}
name:{item2}, time:{2019-05-31T11:58:34.262}
name:{item3}, time:{2019-05-31T11:58:39.262}
上一篇:java随机数生成具体实现代码
栏 目:JAVA代码
下一篇:Java设计模式之原型模式(Prototype模式)介绍
本文地址:http://www.codeinn.net/misctech/77670.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




