Java thread to trigger at multiple timers

时间:2016-05-17 11:21:11

标签: java multithreading thread-sleep

I want to create some sort of alarm clock with multiple alarms (timings) that counts time and notifies me when on different timings:

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

Now this can work ok because i only check time every second which is accurate enough. But i am looking for a more elegant solution like putting the thread to sleep until a certain timer is reached even if it would mean to create another thread.

Is there a more elegant solution than this?

1 个答案:

答案 0 :(得分:1)

由于您知道执行时间,因此您只需使用ScheduledExecutionService

即可
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();

安排任务:

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

使用执行程序服务的好处是所有等待的东西都是在引擎盖下实现的。