java.util.concurrent | DelayQueu
2019-06-27 本文已影响0人
Steven_cao
1、DelayQueue 实现了 BlockingQueue
- 放入其中的元素必须实现java.util.concurrent.Delayed,其接口如下:
public interface Delayed extends Comparable<Delayed>{
/**
* Returns the remaining delay associated with this object, in the
* given time unit.
*
* @param unit the time unit
* @return the remaining delay; zero or negative values indicate
* that the delay has already elapsed
*/
long getDelay(TimeUnit unit);
}
getDelay()方法返回的值 应该是在释放该元素之前剩余的的延迟,如果返回0或负数,则认为延迟已经过期,并在DelayQueue的下一次take()调用时释放元素。
- Delayed接口还继承了java.lang.Comparable接口,这意味着延迟对象可以相互比较,这样就可以在DelayQueue内部用于队列中内部元素的比较,因此可以按过期时间对其排序。
2、DelayQueue的使用
public class DelayQueueDemo {
public static void main(String[] args) {
DelayQueue queue = new DelayQueue();
Delayed element = new DelayedElement();
queue.put(element);
Delayed el = queue.take();
}
}