久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

java中DelayQueue實例用法詳解

瀏覽:2日期:2022-08-18 15:25:44

在阻塞隊里中,除了對元素進行增加和刪除外,我們可以把元素的刪除做一個延遲的處理,即使用DelayQueue的方法。這里的刪除需要一定的時間才能生效,有點類似于過期處理的理念。下面我們就DelayQueue的概念、特點進行講解,然后在代碼示例中體會DelayQueue的使用。

1.概念

是一個帶有延遲時間的無界阻塞隊列。隊列中的元素,只有等延時時間到了,才能取出來。此隊列一般用于過期數(shù)據(jù)的刪除,或任務(wù)調(diào)度。以下,模擬一下定長時間的數(shù)據(jù)刪除。

2.特點

(1)無邊界設(shè)計

(2)添加(put)不阻塞,移除阻塞

(3)元素都有一個過期時間

(4)取元素只有過期的才會被取出

3.實例

每個需要放入DelayQueue隊列元素需要實現(xiàn)Delayed接口,下面我們創(chuàng)建DelayObject 類,其實例對象將被放入DelayQueue中。其構(gòu)造函數(shù)包括字符串類型數(shù)據(jù)及延遲毫秒變量。

public class DelayObject implements Delayed { private String data; private long startTime; public DelayObject(String data, long delayInMilliseconds) { this.data = data; this.startTime = System.currentTimeMillis() + delayInMilliseconds;}

DelayQueue的應(yīng)用實例

package org.dromara.hmily.demo.springcloud.account.service; import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.concurrent.DelayQueue;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit; /** * @description: 延時隊列測試 * @author: hh */public class DelayedQueneTest { public static void main(String[] args) throws InterruptedException { Item item1 = new Item('item1', 5, TimeUnit.SECONDS); Item item2 = new Item('item2',10, TimeUnit.SECONDS); Item item3 = new Item('item3',15, TimeUnit.SECONDS); DelayQueue<Item> queue = new DelayQueue<>(); queue.put(item1); queue.put(item2); queue.put(item3); System.out.println('begin time:' + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); for (int i = 0; i < 3; i++) { Item take = queue.take(); System.out.format('name:{%s}, time:{%s}n',take.name, LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)); } } } class Item implements Delayed{ /* 觸發(fā)時間*/ private long time; String name; public Item(String name, long time, TimeUnit unit) { this.name = name; this.time = System.currentTimeMillis() + (time > 0? unit.toMillis(time): 0); } @Override public long getDelay(TimeUnit unit) { return time - System.currentTimeMillis(); } @Override public int compareTo(Delayed o) { Item item = (Item) o; long diff = this.time - item.time; if (diff <= 0) {// 改成>=會造成問題 return -1; }else { return 1; } } @Override public String toString() { return 'Item{' +'time=' + time +', name=’' + name + ’’’ +’}’; }}

運行結(jié)果:每5秒取出一個

begin time:2019-05-31T11:58:24.445name:{item1}, time:{2019-05-31T11:58:29.262}name:{item2}, time:{2019-05-31T11:58:34.262}name:{item3}, time:{2019-05-31T11:58:39.262}

到此這篇關(guān)于java中DelayQueue實例用法詳解的文章就介紹到這了,更多相關(guān)java中DelayQueue是什么內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 喀喇沁旗| 北宁市| 巴塘县| 安宁市| 德阳市| 绥德县| 石台县| 绥阳县| 张北县| 东莞市| 平利县| 萨迦县| 广宁县| 红河县| 海丰县| 邢台市| 临城县| 南召县| 台山市| 田阳县| 永济市| 灵武市| 九龙县| 藁城市| 桐梓县| 敖汉旗| 常州市| 五常市| 平凉市| 沂水县| 庆安县| 安国市| 老河口市| 江阴市| 凤翔县| 尚义县| 盐源县| 烟台市| 武安市| 庐江县| 杭锦后旗|