Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.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_Timer - Fatal编程技术网

Java定时器帮助?

Java定时器帮助?,java,timer,Java,Timer,我需要用java制作一个无限次运行的计时器,我需要让计时器每2秒运行一次,我该怎么做 您可以使用ScheduledExecutorService ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(); ses.scheduleAtFixedRate(new Runnable() { public void run() { // do something. } },

我需要用java制作一个无限次运行的计时器,我需要让计时器每2秒运行一次,我该怎么做

您可以使用ScheduledExecutorService

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(); 
ses.scheduleAtFixedRate(new Runnable() {
    public void run() {
        // do something.
    }
}, 0, 2, TimeUnit.SECONDS);

您可以使用ScheduledExecutorService

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor(); 
ses.scheduleAtFixedRate(new Runnable() {
    public void run() {
        // do something.
    }
}, 0, 2, TimeUnit.SECONDS);
你可以用

你可以用

我以前使用过类似的功能,它对我很有效。

我以前使用过类似的功能,它对我很有效

public class Timer implements Runnable {

public static void main(String args[]) {
    Timer t = new Timer();
    t.run();
}

public void run() {
    while (true) {
        //do something cool            
       try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            //handle interrupt
        }
    }
}
}

像这样的

}


像这样的吗?

无限次?你会在这里呆一段时间!Google Java Timer为您提供了Java中的Timer类,为什么不使用它呢@Roy我试过这么做,但我没弄明白,我试过:Timer Timer=new Timer(2000,new Timer handler()),但是它给了我一个我自己无法修复的错误。老实说,与C#one相比,Java计时器过于复杂,但是宏给出了一个很好的例子,Java计时器教程也会给你很多很好的例子。无限次?你会在这里呆一段时间!Google Java Timer为您提供了Java中的Timer类,为什么不使用它呢@Roy我试过这么做,但我没弄明白,我试过:Timer Timer=new Timer(2000,new Timer handler()),但它给了我一个我自己无法修复的错误。老实说,与C#one相比,Java计时器过于复杂,但是宏给出了一个很好的例子,Java计时器教程也会给你很多很好的例子。
ScheduledExecutorService
是更好的选择。读一读,你就会知道为什么。我不明白为什么。能否请您添加一个简短的解释?如果任务完成所需时间超过
时间
,后续任务将开始排队,一旦该任务完成,排队的任务将快速连续启动,并导致行为不稳定。这不会发生在ScheduledExecutorService上。@sthupahsmat:我明白了。谢谢你的解释。我将来一定要记住这一点<代码>ScheduledExecutorService是更好的选择。读一读,你就会知道为什么。我不明白为什么。能否请您添加一个简短的解释?如果任务完成所需时间超过
时间
,后续任务将开始排队,一旦该任务完成,排队的任务将快速连续启动,并导致行为不稳定。这不会发生在ScheduledExecutorService上。@sthupahsmat:我明白了。谢谢你的解释。我将来一定要记住这一点!