DelayQueue:
JDK自带的延迟队列,基于阻塞队列实现。 |
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;//延迟任务 例子:
public class MyDelayedTask implements Delayed {//任务的执行时间private int executeTime =0 ; //代表元素执行时间private String name;//元素名称/**** @param delay 元素延迟多久执行* @param name 元素名称*/public MyDelayedTask(int delay, String name) {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.SECOND,delay);this.executeTime = (int)(calendar.getTimeInMillis()/1000);this.name = name;}/*** 元素在队列中的剩余时间* @param unit the time unit* @return*/@Overridepublic long getDelay(TimeUnit unit) {Calendar calendar = Calendar.getInstance();return executeTime-(calendar.getTimeInMillis()/1000);}/*** 元素排序* @param o the object to be compared.* @return*/@Overridepublic int compareTo(Delayed o) {long val = this.getDelay(TimeUnit.NANOSECONDS)-o.getDelay(TimeUnit.NANOSECONDS);return val == 0? 0:(val<0? -1:1);}@Overridepublic String toString(){return "MyDelayedTask{" +"executeTime=" + executeTime +",name='"+name+'\'' +'}';}public static void main(String[] args) throws InterruptedException {DelayQueue<MyDelayedTask> queue = new DelayQueue<MyDelayedTask>();//延迟阻塞队列queue.add(new MyDelayedTask(10,"李四"));queue.add(new MyDelayedTask(5,"张三"));queue.add(new MyDelayedTask(15,"王五"));System.out.println(new Date() + " start consume ");while (queue.size()!=0){// MyDelayedTask delayedTask = queue.poll();//从队列中拉取元素 poll 非阻塞方法MyDelayedTask delayedTask = queue.take(); //从队列中拉取元素 take 阻塞方法System.out.println(new Date()+" consume task "+delayedTask);//每隔一秒消费一次try {Thread.sleep(1000);}catch (InterruptedException e ){e.printStackTrace();}}}
}