XML Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
package com.lyzx.day02;
import java.util.concurrent.DelayQueue; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Throws exception Special value Blocks Times out * Insert add(e) offer(e) put(e) offer(e, time, unit) * Remove remove() poll() take() poll(time, unit) * *DelayQueue <E extends Delayed>延迟队列 * 这个队列里面存放的都是Delayed(接口) * Delayed接口继承了Comparable接口,因为其内部使用PriorityQueue存放元素,所以 * 需要实现PriorityQueue以排序 * * DelayQueue取出元素的顺序是按照getDelay()的返回的大小 * 越小的排在越前面 * 然后按照getDelay()返回的数值N以及单位在当前时间的N个单位后被take()取出 * / public class T3 { public static void main(String[] args){ DelayQueue <Task> queue = new DelayQueue <Task>(); long now = System.currentTimeMillis(); System.out.println( "now:::::"+now); queue.put(new Task( "t4",now +4000)); queue.put(new Task( "t1",now +1000)); queue.put(new Task( "t3",now +3000)); ExecutorService es = Executors.newCachedThreadPool(); //对DelayQueue遍历,使用take这个阻塞方法取出延迟时间到了的元素 //Task也实现了Runnable接口所以当取出这个任务时就可以交给提前准备好的线程池 //去执行这个任务 while(queue.size() > 0){ try { Task task = queue.take(); System.out.println( "task:"+task); es.execute(task); } catch (InterruptedException e) { e.printStackTrace(); } } es.shutdown(); } } class Task implements Runnable,Delayed{ private final String name ; private final long trigger; public Task(String name,long tigger){ this.name=name; this.trigger=tigger; } @Override public int compareTo(Delayed o) { Task target = (Task)o; if(this.trigger > target.trigger) return 1; if(this.trigger < target.trigger) return -1; return 0; } /** * 这个方法用于把延迟时间和当前时间的差转换为对应的时间 * 至于unit到底是哪一种TimeUnit,不需要使用者知道 * 注意:如果延迟 /触发时间trigger用毫秒表示则第一个参数为 * trigger-System.currentTimeMillis() * 如果trigger用纳秒表示则则第一个参数为 * trigger-System.nanoTime() * / @Override public long getDelay(TimeUnit unit){ long r = unit.convert(trigger-System.currentTimeMillis(),TimeUnit.MILLISECONDS); return r; } @Override public void run(){ System.out.println( "now:"+System.currentTimeMillis()+ " name:"+name+ " trigger:"+trigger); } @Override public String toString() { return "Task [name=" + name + ", trigger=" + trigger + "]"; } } |