package concurrentTest;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
/**
* Created by mashao on 15/9/23.
*/
public class TestDelayQueue {
static class Element implements Delayed {
private long trigger;
private int id;
public long getTrigger() {
return this.trigger;
}
public int getId() {
return this.id;
}
Element(long i, int id) {
trigger = System.currentTimeMillis() + i;
this.id = id;
}
public long getDelay(TimeUnit unit) {
return trigger - System.currentTimeMillis();
}
public int compareTo(Delayed o) {
return (int)(this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
}
}
public static void main(String[] args) {
DelayQueue<Element> queue = new DelayQueue<Element>();
queue.add(new Element(1000L, 1));
queue.add(new Element(500L, 2));
long start = System.currentTimeMillis();
while (!queue.isEmpty()) {
try {
Element element = queue.take();
long period = System.currentTimeMillis() - start;
System.out.println(period + ":" + element.getId());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
DelayQueue
最新推荐文章于 2024-06-25 11:29:32 发布