1.创建实体类 实现 Delayed 接口
public class OrderInfo implements Serializable, Delayed { private static final long serialVersionUID = 1L; /** * 订单号 */ private String orderNo; /** * 订单状态 */ private String status; /** * 订单过期时间 */ private Long expTime; /** * 订单创建时间 */ private Long createTime;
//省略set get 方法
。。。。。。
@Override public int compareTo(Delayed o) { OrderInfo orderInfo= (OrderInfo) o; return orderInfo.getCreateTime().compareTo(orderInfo.getExpTime()); } /** * 时间单位:秒 * 延迟关闭时间 = 过期时间 - 当前时间 */ @Override public long getDelay(TimeUnit unit) { return this.getExpTime() - System.currentTimeMillis(); }
2.编写测试类
public class TestMain { public static void main(String[] args) throws InterruptedException { DelayQueue<OrderInfo> queue=new DelayQueue<>(); OrderInfo orderInfo=new OrderInfo(); orderInfo.setOrderNo("1"); orderInfo.setStatus("test"); orderInfo.setCreateTime(System.currentTimeMillis()); System.out.println("加入队列时间====》》》"+new Date()); orderInfo.setExpTime(System.currentTimeMillis()+20*1000); queue.put(orderInfo); while (true){ OrderInfo take = queue.take(); System.out.println(take); System.out.println("取出队列时间====》》》"+new Date()); } }
测试结果