Java線程池隊列DelayQueue的使用詳解
Java線程池隊列DelayQueue的使用及詳細介紹
一、什么是DelayQueue?
DelayQueue顧名思義,它是個無邊界延遲隊列,它的底層是基于PriorityBlockingQueue實現(xiàn)的。
該隊列中的元素都是按照過期時間順序排序的,隊列頭部放的是即將過期的元素。
該隊列中的元素必須實現(xiàn)Delayed接口,getDelay定義了剩余到期時間,compareTo方法定義了元素排序規(guī)則。
該隊列不允許存放null元素。延時隊列實現(xiàn)了Iterator接口,但Iterator()遍歷順序不保證是元素的實際存放順序。
總結(jié)
- DelayQueue隊列是無邊界
- 隊列中按照過期時間排序
- 隊列中的元素必須實現(xiàn)Delayed接口
- 不允許存放null元素
- poll方法獲取元素時,立即返回,如果沒有過期的元素則返回null
- take方法獲取元素時,如果沒有過期的元素則會進行阻塞
- peek方法獲取元素時,立即返回,不會刪除該元素,即使沒有過期的元素也會獲取到
- 使用Iterator可以立即返回該隊列中的元素,但是不保證順序
二、案例
package com.brycen.part3.threadpool.collections;
import java.util.Iterator;
import java.util.concurrent.*;
public class DelayQueueExample {
public static void main(String[] args) throws InterruptedException {
DelayQueue<DelayElement> delayQueue = new DelayQueue<>();
delayQueue.add(new DelayElement<String>("test1",1000));
delayQueue.add(new DelayElement<String>("test2",800));
delayQueue.add(new DelayElement<String>("test3",2000));
delayQueue.add(new DelayElement<String>("test4",3000));
System.out.println("隊列大小:"+delayQueue.size());
//立即返回,同時刪除元素,如果沒有過期元素則返回null
System.out.println("poll方法獲?。?+delayQueue.poll());
//立即返回,不會刪除元素,如果沒有過期元素也會返回該元素,只有當隊列為null時才會返回null
System.out.println("peek方法獲?。?+delayQueue.peek());
//進行阻塞
System.out.println("take方法獲取:"+delayQueue.take().getData());
//立即返回,但不能保證順序
Iterator<DelayElement> iterator = delayQueue.iterator();
while (iterator.hasNext()){
DelayElement element = iterator.next();
System.out.println("iterator獲?。?+element.getData());
}
}
static class DelayElement<E> implements Delayed{
private final long expireTime;
private final E e;
public DelayElement(E e,long delay) {
this.expireTime = System.currentTimeMillis()+delay;
this.e = e;
}
@Override
public long getDelay(TimeUnit unit) {
//判斷是否過期
return unit.convert(expireTime-System.currentTimeMillis(),TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed delayed) {
//排序規(guī)則:按照過期時間排序
DelayElement that = (DelayElement)delayed;
if (this.expireTime<that.expireTime){
return -1;
}else if (this.expireTime>that.expireTime){
return 1;
}else {
return 0;
}
}
public E getData() {
return e;
}
}
}運行結(jié)果:
隊列大?。?
poll方法獲取:null
peek方法獲?。篶om.brycen.part3.threadpool.collections.ArrayBlockingQueueExample$DelayElement@2437c6dc
take方法獲?。簍est2
iterator獲取:test1
iterator獲?。簍est4
iterator獲取:test3
到此這篇關(guān)于Java線程池隊列DelayQueue的使用詳解的文章就介紹到這了,更多相關(guān)Java線程池隊列DelayQueue內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java并發(fā)編程之詳解CyclicBarrier線程同步
在之前的文章中已經(jīng)為大家介紹了java并發(fā)編程的工具:BlockingQueue接口,ArrayBlockingQueue,DelayQueue,LinkedBlockingQueue,PriorityBlockingQueue,SynchronousQueue,BlockingDeque接口,ConcurrentHashMap,CountDownLatch,本文為系列文章第十篇,需要的朋友可以參考下2021-06-06
java中將一個List等分成n個list的工具方法(推薦)
下面小編就為大家?guī)硪黄猨ava中將一個List等分成n個list的工具方法(推薦)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03
java調(diào)用微信接口實現(xiàn)網(wǎng)頁分享小功能
這篇文章主要為大家詳細介紹了java調(diào)用微信接口實現(xiàn)網(wǎng)頁分享小功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04

