Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要在多个计时器上触发的Java线程_Java_Multithreading_Thread Sleep - Fatal编程技术网

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

要在多个计时器上触发的Java线程,java,multithreading,thread-sleep,Java,Multithreading,Thread Sleep,我想创建一种带有多个闹钟(计时)的闹钟,用于计算时间并在不同计时时通知我: 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 : timing

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

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
    }
}
私有列表定时//也可以只是数秒
公开募捐{
同时(计数){
//如果达到任何时间点,请采取行动
用于(某个时间:计时){
if(time.equals(System.getTime()){
triggerEvent();
}
}
Thread.sleep(1000);//等待1秒
}
}
现在这可以正常工作了,因为我每秒只检查一次时间,这足够精确。但是我正在寻找一个更优雅的解决方案,比如让线程休眠,直到达到某个计时器,即使这意味着要创建另一个线程


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

因为您知道执行时间,所以可以简单地使用ScheduledExecutionService

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
要安排任务,请执行以下操作:

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

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

为什么不使用java的计时器框架?@Gobliins您不能更改它,但可以取消任务并安排一个新的任务。schedule方法返回具有cancel方法的Future。我理解。所以我想,对于r单个线程?@Gobliins exec service可以有任意多个线程。您可以将多个任务安排到单个服务。许多事情都是可配置的,我只是不知道您的要求,您最初的问题很简单。