【java多线程】队列系统之DelayQueue源码
一、延迟队列
延迟队列,底层依赖了优先级队列PriorityBlockingQueue
二、延迟队列案例
(1)延迟队列的任务
public class DelayTask implements Delayed { /** * 要执行的任务 */ private String doTask; /** * 任务要执行的时间 */ private Date date; /** * 还剩多长时间,开始执行任务 * @param unit * @return */ @Override public long getDelay(TimeUnit unit) { return unit.convert(date.getTime()-System.currentTimeMillis(),unit) ; } /** * 当前对象,跟其他延时任务比,谁更先被触发 * @param o * @return */ @Override public int compareTo(Delayed o) { if(o instanceof DelayTask){ Date otherDate= ((DelayTask) o).getDate(); long a= date.getTime()-otherDate.getTime(); if(a>0){ return 1; }else if(a<0){ return -1; }else{ return 0; } }else{ throw new RuntimeException("队列数据异常"); } } public String getDoTask() { return doTask; } public void setDoTask(String doTask) { this.doTask = doTask; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
(2)延迟队列的消费线程
public class DelayTaskThread extends Thread{ private DelayQueue<DelayTask> delayTasksQueue; public DelayTaskThread(DelayQueue<DelayTask> delayTasksQueue ){ this.delayTasksQueue=delayTasksQueue; } @Override public void run() { System.out.println("===========线程开始运行====="); while (true){ try { DelayTask delayTask=delayTasksQueue.take(); System.out.println(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss")+"获取任务成功"); Date date =delayTask.getDate(); String task=delayTask.getDoTask(); System.out.println(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss")+"=====>要执行的任务内容为【"+task+"】到期时间为【"+ DateFormatUtils.format(date,"yyyy-MM-dd HH:mm:ss")+"】"); Arrays.asList("a","b"); } catch (InterruptedException e) { e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } } } }