1. Create an entity class that implements the interface Delayed
OrderInfo the implements the Serializable class public, the DelayedPause { Private Long Final static serialVersionUID = 1L; / ** * Order number * / Private String orderNo; / ** * Order Status * / Private String Status; / ** * expiration time line * / Private exptime Long; / ** * order creation time * / Private Long createTime;
// omitted set get method
. . . . . .
@Override public int the compareTo (the DelayedPause O) { OrderInfo the orderInfo = (OrderInfo) O; return orderInfo.getCreateTime () the compareTo (orderInfo.getExpTime ()).; } / ** * time unit: s * = off-time delay expires - the current time * / @Override public Long getDelay (TimeUnit Unit) { return this.getExpTime () - System.currentTimeMillis (); }
2. Write a test class
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()); } }
Test Results