java.util.concurrent | DelayQueue

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();
     }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容