DelayEvent.java
public class DelayEvent2 implements Delayed { //到期时间 private Date startDate; public DelayEvent2(Date startDate) { this.startDate = startDate; } public int compareTo(Delayed o){ long result = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS); if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } /** * 返回与此对象相关的剩余延迟时间,以给定的时间单位表示 */ public long getDelay(TimeUnit unit){ Date now = new Date(); long diff = startDate.getTime() - now.getTime(); return unit.convert(diff, TimeUnit.MILLISECONDS); } }
DelayTask.java
/** * 任务任务 * 作用:添加100个新DelayEvent到DelayQueue队列中 */ public class DelayTask2 implements Runnable{ //添加时间 private int id; //队列 private DelayQueue<DelayEvent2> dq = new DelayQueue<DelayEvent2>(); public DelayTask2(int id, DelayQueue<DelayEvent2> dq) { this.id = id; this.dq = dq; } public void run() { //旧Date Date date = new Date(); //新Date Date delay = new Date(); delay.setTime(date.getTime() + id * 1000); System.out.println("Thread 时间+:" + id + " 新Date:" + delay); //将100个DelayEvent放入DelayQueue for(int i = 0;i < 100;i++){ DelayEvent2 de = new DelayEvent2(delay); dq.add(de); } } }
DelayDequeueMain.java
public class DelayDequeMain2 { public static void main(String[] args) throws Exception{ DelayQueue<DelayEvent2> dq = new DelayQueue<DelayEvent2>(); Thread threads[] = new Thread[5]; for(int i = 0;i < threads.length;i++){ DelayTask2 task = new DelayTask2(i+1,dq); threads[i] = new Thread(task); } for(int i = 0;i < threads.length;i++){ threads[i].start(); } for(int i = 0;i < threads.length;i++){ threads[i].join(); } do{ int counter = 0; DelayEvent2 delayEvent2; do{ delayEvent2 = dq.poll(); if(delayEvent2 != null){ counter++; } }while(delayEvent2!=null); System.out.println("At " + new Date() + " you have read " + counter + " event"); TimeUnit.MILLISECONDS.sleep(500); }while(dq.size()>0); } }