gpt4 book ai didi

java - 我如何设置 DelayQueue 的延迟

转载 作者:搜寻专家 更新时间:2023-11-01 01:16:58 24 4
gpt4 key购买 nike

我刚开始用 java 编码,我正在努力设置 DelayQueue,

我想这样,

DelayQueue queue = new DelayQueue();

If (counter > 0){
queue.offer(Integer, *A custom delay*)
} Else {
queue.offer(Integer, *A different custom delay*)
}

我只是想学习所有基础知识,我已经通读了 API,但似乎无法掌握它。

提前致谢

最佳答案

Delayed 的这种实现很好,因为:

  • compareTo() 的实现不进行任何类转换,消除了抛出 ClassCastException
  • 的可能性
  • compareTo() 的实现在转换为 int 之前使用 Math.minMath.max 函数为了正确防止溢出错误
  • getDelay() 的实现正确地转换了单位并实际返回剩余时间

TestDelay 类实现Delayed:

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class TestDelay implements Delayed
{
public final Long delayMillis;
public final Long expireTimeMillis;

public TestDelay(Long delayMillis)
{
this.delayMillis = delayMillis;
this.expireTimeMillis = System.currentTimeMillis()+delayMillis;
}

@Override
public final int compareTo(@NotNull Delayed o)
{
long diffMillis = getDelay(TimeUnit.MILLISECONDS)-o.getDelay(TimeUnit.MILLISECONDS);
diffMillis = Math.min(diffMillis,1);
diffMillis = Math.max(diffMillis,-1);
return (int) diffMillis;
}

@Override
public final long getDelay(@NotNull TimeUnit unit)
{
long delayMillis = expireTimeMillis-System.currentTimeMillis();
return unit.convert(delayMillis,TimeUnit.MILLISECONDS);
}
}

JUnit 单元测试显示了使用 TestDelay 类的示例:

import org.junit.Test;

import java.util.concurrent.DelayQueue;

public class DelayQueueTest
{
@Test
public final void generalTest() throws InterruptedException
{
DelayQueue<TestDelay> q = new DelayQueue<>();
q.put(new TestDelay(500L));
q.put(new TestDelay(2000L));
q.put(new TestDelay(1000L));
q.put(new TestDelay(10L));
q.put(new TestDelay(3000L));
while (!q.isEmpty())
{
System.out.println(q.take().delayMillis);
}
}
}

DelayQueueTest 的输出:

unit test output

关于java - 我如何设置 DelayQueue 的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23219801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com