gpt4 book ai didi

Java线程在多个计时器上触发

转载 作者:行者123 更新时间:2023-11-30 07:22:45 27 4
gpt4 key购买 nike

我想创建某种带有多个闹钟(计时)的闹钟,它可以计算时间并在不同的计时时通知我:

private List<SomeTime> timings; //can also be just the seconds to count

public void run() {
while(counting) {
//if any of the timings is reached do something
for (SomeTime time : timings) {
if(time.equals(System.getTime()) {
triggerEvent();
}
}
Thread.sleep(1000); //wait 1 second
}
}

现在这可以正常工作,因为我只每秒检查一次时间,这已经足够准确了。但我正在寻找一种更优雅的解决方案,例如将线程置于 sleep 状态,直到达到某个计时器,即使这意味着创建另一个线程。

还有比这更优雅的解决方案吗?

最佳答案

既然你知道执行时间,你可以简单地使用ScheduledExecutionService

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

安排任务:

long currentTimeMs = System.currentTimeMillis();
long delayMs = task.getTime() - currentTimeMs;
ses.schedule(eventRunnable, delayMs, TimeUnit.MILLISECONDS);

使用执行器服务的好处是所有等待的东西都是在后台实现的。

关于Java线程在多个计时器上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37274667/

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