我如何设置延迟队列的延迟

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

这篇关于我如何设置延迟队列的延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我如何设置延迟队列的延迟

基础教程推荐