How do i set up a DelayQueue#39;s Delay(我如何设置延迟队列的延迟)
问题描述
我刚开始用 java 编码,我正在努力设置延迟队列,
我想拥有它,
DelayQueue queue = new DelayQueue();如果(计数器 > 0){queue.offer(Integer, *自定义延迟*)} 别的 {queue.offer(Integer, *不同的自定义延迟*)}
我只是想学习所有基础知识,但我阅读了 API,但似乎无法掌握它.
提前致谢
解决方案
DelayQueue
在内部保留元素,直到某个延迟到期.元素必须实现接口java.util.concurrent.Delayed
.例如我创建了一个类
DelayedTest
扩展延迟接口.这将实现 compareTo 和 getDelay() 方法公共类 A{公共静态无效主(字符串...参数){延迟队列 dq=新延迟队列();DeleyedTest ob1=new DeleyedTest(10);DeleyedTest ob2=new DeleyedTest(5);DeleyedTest ob3=new DeleyedTest(15);dq.offer(ob1);dq.offer(ob2);dq.offer(ob3);迭代器 itr=dq.iterator();而(itr.hasNext()){DeleyedTest dt=(DeleyedTest)itr.next();System.out.println(dt.deleyTime);}}}类 DeleyedTest 实现延迟{公共长deleyTime=0;DeleyedTest(long deleyTime){this.deleyTime=deleyTime;}@覆盖公共 int compareTo(延迟 ob){if(this.deleyTime<((DeleyedTest)ob).deleyTime){返回-1;}else if(this.deleyTime>((DeleyedTest)ob).deleyTime){返回 1;}返回0;}@覆盖public long getDelay(TimeUnit unit) {返回 unit.convert(deleyTime-System.currentTimeMillis(),TimeUnit.NANOSECONDS);}}
结果:
<上一页>51015
I'm just starting out coding in java i'm in struggling with setting up a DelayQueue,
I wanted to have it so,
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.
Thanks in advance
The DelayQueue
keeps the elements internally until a certain delay has expired. The elements must implement the interface java.util.concurrent.Delayed
.
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);
}
}
Result:
5 10 15
这篇关于我如何设置延迟队列的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我如何设置延迟队列的延迟
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01