【问题标题】:Java thread to trigger at multiple timers在多个计时器处触发的 Java 线程
【发布时间】:2016-05-17 11:21:11
【问题描述】:

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

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
    }
}

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

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

【问题讨论】:

标签: java multithreading thread-sleep


【解决方案1】:

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

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

要安排任务:

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

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

【讨论】:

  • @Gobliins 你不能改变它,但你可以取消任务并安排一个新的。 schedule 方法返回具有取消方法的 Future。
  • 我明白了。所以我想,单个线程也不可能有多个时间?
  • @Gobliins exec 服务可以拥有任意数量的线程。您可以将多个任务安排到单个服务。很多东西都是可配置的,我只是不知道你的要求,你最初的问题很简单。
猜你喜欢
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多