DelayQueue是一個(gè)無界阻塞隊(duì)列,可以用做延時(shí)處理,所謂延時(shí)處理就是說可以為隊(duì)列中元素設(shè)定一個(gè)過期時(shí)間,其中的元素只有在時(shí)間到期時(shí)才能從中被提取。該隊(duì)列的頭部是延遲期滿后保存時(shí)間最長(zhǎng)的Delayed 元素忱嘹。存放到DelayDeque的元素必須繼承Delayed接口。Delayed接口使對(duì)象成為延遲對(duì)象耕渴,它使存放在DelayQueue類中的對(duì)象具有了激活日期拘悦。該接口強(qiáng)制實(shí)現(xiàn)下列兩個(gè)方法。
- CompareTo(Delayed o) :Delayed接口繼承了Comparable接口橱脸,因此有了這個(gè)方法
- getDelay(TimeUnit unit):這個(gè)方法返回到激活日期的剩余時(shí)間础米,時(shí)間單位由單位參數(shù)指定分苇。
簡(jiǎn)單使用
實(shí)現(xiàn)一個(gè)延遲任務(wù)
public class DelayedTask implements Delayed{
/**
* 延遲時(shí)間
*/
private final long delayTime;
/**
* 到期時(shí)間
*/
private final long expire;
/**
* 數(shù)據(jù)
*/
private String data;
public DelayedTask(long delayTime,String data){
this.delayTime=delayTime;
this.data=data;
// 過期時(shí)間為:當(dāng)前系統(tǒng)時(shí)間+延遲時(shí)間
this.expire=System.currentTimeMillis()+delayTime;
}
@Override
public long getDelay(@NotNull TimeUnit unit) {
return unit.convert(this.expire - System.currentTimeMillis() , TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(@NotNull Delayed o) {
return (int) (this.getDelay(TimeUnit.MILLISECONDS) -o.getDelay(TimeUnit.MILLISECONDS));
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("DelayedElement{");
sb.append("delay=").append(delayTime);
sb.append(", expire=").append(expire);
sb.append(", data='").append(data).append('\'');
sb.append('}');
return sb.toString();
}
}
使用延遲隊(duì)列
public class DelayedQueueStudy {
public static void main(String[] args){
DelayQueue delayQueue =new DelayQueue<DelayedTask>();
DelayedTask delayedTask=new DelayedTask(5000,"abc");
DelayedTask delayedTask1=new DelayedTask(3000,"def");
delayQueue.offer(delayedTask);
delayQueue.offer(delayedTask1);
long startTime=System.currentTimeMillis();
while (true){
try {
Delayed delayedtask=delayQueue.take();
System.out.println(delayedtask);
long endTime=System.currentTimeMillis();
System.out.println("用時(shí)總時(shí)間"+(endTime-startTime));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}