gpt4 book ai didi

java - Netty HashedWheelTimer 意外行为。提前超时触发

转载 作者:行者123 更新时间:2023-12-01 05:50:09 27 4
gpt4 key购买 nike

让我们考虑一下这种情况:

import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;


Timer timer = new HashedWheelTimer();
Timeout timeout = null;

void establishTimeout() {
timeout = timer.newTimeout(timerTask, delay, TimeUnit.SECONDS);
}

void cancelTimeout() {
timeout.cancel()
timeout = null;
}

public static void main(String[] args) {
establishTimeout();
cancelTimeout();
Thread.sleep(sleepDelay);
establishTimeout();
}

时间线上发生了什么:

0          : establishTimeout(), cancelTimeout()
sleepDelay : establishTimeout()
delay : timerTask.run()

为什么timerTask没有在sleepDelay+delay处运行?如何让它按预期工作?

最佳答案

因为 delay 被解释为秒,而 sleepDelay 被解释为毫秒。使用 sleepDelay * 1000 获得您想要的结果。

public class TaskTester {

static Timer timer = new HashedWheelTimer();
static Timeout timeout = null;
static int delay = 3;
static int sleepDelay = 2;
static TimerTask timerTask = new TimerTask(){
public void run(Timeout timeout) throws Exception {
System.out.printf("RUN %.3f%n", System.currentTimeMillis() / 1000.0);
}
};

static void establishTimeout() {
timeout = timer.newTimeout(timerTask, delay, TimeUnit.SECONDS);
}

static void cancelTimeout() {
timeout.cancel();
timeout = null;
}

public static void main(String[] args) throws InterruptedException {
System.out.printf("START %.3f%n", System.currentTimeMillis() / 1000.0);
establishTimeout();
cancelTimeout();
Thread.sleep(sleepDelay * 1000);
establishTimeout();
System.out.printf("MAIN DONE %.3f%n", System.currentTimeMillis() / 1000.0);
}
}

关于java - Netty HashedWheelTimer 意外行为。提前超时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4920104/

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