作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想创建某种带有多个闹钟(计时)的闹钟,它可以计算时间并在不同的计时时通知我:
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/
我是一名优秀的程序员,十分优秀!