java - 為什么我的延遲隊列取不出數據了?
問題描述
我使用java的延遲隊列來取數據,但是發現根本無法取出數據。
package com.test;import java.util.concurrent.Delayed;import java.util.concurrent.TimeUnit;public class SmsEntity implements Delayed { private final long WAIT_TIME = 10; private long startTime = System.currentTimeMillis(); private String phone; public SmsEntity(String phone) {this.phone = phone; } public String getPhone() {return phone; } public void setPhone(String phone) {this.phone = phone; } public long getStartTime() {return startTime; } public void setStartTime(long startTime) {this.startTime = startTime; } @Override public int compareTo(Delayed o) {SmsEntity entity = (SmsEntity) o;if (this.getStartTime() - entity.getStartTime() > 0) { return 1;}return -1; } @Override public long getDelay(TimeUnit unit) {//long waitTimeForGiveTimeUnit = unit.convert(WAIT_TIME, TimeUnit.MILLISECONDS);//long areadyLeftTime = unit.convert(System.currentTimeMillis(), TimeUnit.MILLISECONDS)//- unit.convert(startTime, TimeUnit.MILLISECONDS);//if (areadyLeftTime > waitTimeForGiveTimeUnit) {// return 0;//}//return unit.convert(waitTimeForGiveTimeUnit - areadyLeftTime, TimeUnit.MILLISECONDS);return 1; }}package com.test;import java.util.concurrent.DelayQueue;public class DelayQueueDemo { public static void main(String[] args) {DelayQueue<SmsEntity> queue=new DelayQueue<>();queue.put(new SmsEntity('1'));try {// Thread.sleep(3000); queue.put(new SmsEntity('2')); System.out.println(queue.take().getPhone()); System.out.println(queue.take().getPhone());} catch (InterruptedException e) { e.printStackTrace();} }}
結果是一直在阻塞。我想請教這是為什么,感覺自己調用的沒有錯啊
問題解答
回答1:getDelay()始終返回1,所以永遠不會expire。
可以仔細研究一下DelayQueue的文檔: https://docs.oracle.com/javas...
Expiration occurs when an element’s getDelay(TimeUnit.NANOSECONDS)method returns a value less than or equal to zero
相關文章:
1. android - NavigationView 的側滑菜單中如何保存新增項(通過程序添加)2. python - Pycharm一句代碼寫完可以自動補全空格么?3. 提示語法錯誤語法錯誤: unexpected ’abstract’ (T_ABSTRACT)4. python - xpath提取網頁路徑沒問題,但是缺失內容?5. mysql服務無法啟動1067錯誤,誰知道正確的解決方法?6. tp5 不同控制器中的變量調用問題7. 除了 python2 和 python3,ipython notebook 還可以用哪些內核?8. php7.3.4中怎么開啟pdo驅動9. 這段代碼既不提示錯誤也看不到結果,請老師明示錯在哪里,謝謝!10. 老師 我是一個沒有學過php語言的準畢業生 我希望您能幫我一下
