本文介绍了如何设置DelayQueue的延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚开始使用Java进行编码,我正努力设置DelayQueue,
I'm just starting out coding in java i'm in struggling with setting up a DelayQueue,
我想这样做,
DelayQueue queue = new DelayQueue();
If (counter > 0){
queue.offer(Integer, *A custom delay*)
} Else {
queue.offer(Integer, *A different custom delay*)
}
我只是在尝试学习所有基础知识
I'm just trying to learn all the basics and ive read over the API and cant seem to grasp it.
预先感谢
推荐答案
DelayQueue
在内部保留元素,直到达到一定的延迟为止。元素必须实现 java.util.concurrent.Delayed
接口。
The DelayQueue
keeps the elements internally until a certain delay has expired. The elements must implement the interface java.util.concurrent.Delayed
.
例如,我创建了一个类 DelayedTest
扩展了Delayed接口。这将实现compareTo和getDelay()方法
For example I have created a class DelayedTest
extending Delayed interface. This will implement compareTo and getDelay() method
public class A{
public static void main(String... args){
DelayQueue dq=new DelayQueue();
DeleyedTest ob1=new DeleyedTest(10);
DeleyedTest ob2=new DeleyedTest(5);
DeleyedTest ob3=new DeleyedTest(15);
dq.offer(ob1);
dq.offer(ob2);
dq.offer(ob3);
Iterator itr=dq.iterator();
while(itr.hasNext()){
DeleyedTest dt=(DeleyedTest)itr.next();
System.out.println(dt.deleyTime);
}
}
}
class DeleyedTest implements Delayed{
public long deleyTime=0;
DeleyedTest(long deleyTime){
this.deleyTime=deleyTime;
}
@Override
public int compareTo(Delayed ob) {
if(this.deleyTime<((DeleyedTest)ob).deleyTime){
return -1;
}else if(this.deleyTime>((DeleyedTest)ob).deleyTime){
return 1;
}
return 0;
}
@Override
public long getDelay(TimeUnit unit) {
return unit.convert(deleyTime-System.currentTimeMillis(),TimeUnit.NANOSECONDS);
}
}
结果:
5
10
15
这篇关于如何设置DelayQueue的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!