/**
* 自定義延遲隊列
* @author xulihui
* @date 2020/4/12 19:07
*/
public class CustomDelayQueue {
// 延遲消息隊列
private static DelayQueue delayQueue = new DelayQueue();
// 生產者
public static void producer() {
// 添加消息
delayQueue.put(new Delay(2000,"1"));
delayQueue.put(new Delay(10000,"1"));
}
// 消費者
public static void consumer() throws Exception {
System.out.println("開始執行時間:"+ DateFormat.getDateTimeInstance().format(new Date()));
while (!delayQueue.isEmpty()) {
System.out.println(delayQueue.take());
}
System.out.println("結束執行時間:"+ DateFormat.getDateTimeInstance().format(new Date()));
}
static class Delay implements Delayed {
long delayTime = System.currentTimeMillis();
private String msg ;
public Delay (long delayTime,String msg) {
this.delayTime =(this.delayTime+ delayTime);
this.msg =msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
// 獲取剩餘時間
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(delayTime -System.currentTimeMillis(),TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
if (this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {
return 1;
} else if (this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {
return -1;
} else {
return 0;
}
}
@Override
public String toString() {
return "Delay{" +
"delayTime=" + delayTime +
", msg='" + msg + '\'' +
'}';
}
}
public static void main(String[] args) throws Exception {
// 生產者
producer();
//消費者
consumer();
}
}