温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

DelayQueue怎么在java项目中使用

发布时间:2021-01-12 14:50:55 来源:亿速云 阅读:115 作者:Leah 栏目:开发技术

这篇文章将为大家详细讲解有关DelayQueue怎么在java项目中使用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

1.概念

DelayQueue是一个带有延迟时间的无界阻塞队列。队列中的元素,只有等延时时间到了,才能取出来。此队列一般用于过期数据的删除,或任务调度。以下,模拟一下定长时间的数据删除。

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}

关于DelayQueue怎么在java项目中使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI