我使用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();
}
}
}
结果是一直在阻塞。我想请教这是为什么,感觉自己调用的没有错啊
getDelay()始终返回1,所以永远不会expire。
可以仔细研究一下DelayQueue的文档: https://docs.oracle.com/javas...