如何延迟Java? [英] How do I make a delay in Java?
问题描述
我正在尝试用Java做一些事情,我需要在while循环中等待/延迟一段时间。
I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.
while (true) {
if (i == 3) {
i = 0;
}
ceva[i].setSelected(true);
// I need to wait here
ceva[i].setSelected(false);
// I need to wait here
i++;
}
我想构建一个步序器,我是Java的新手。有什么建议吗?
I want to build a step sequencer and I'm new to Java. Any suggestions?
推荐答案
如果你想暂停,那就用 java.util.concurrent.TimeUnit
:
If you want to pause then use java.util.concurrent.TimeUnit
:
TimeUnit.SECONDS.sleep(1);
睡一秒或
TimeUnit.MINUTES.sleep(1);
睡一分钟。
由于这是一个循环,这提出了一个固有的问题 - 漂移。每次你运行代码然后再睡觉时,你会每隔一秒就跑步一次。如果这是一个问题,那么不要使用 sleep
。
As this is a loop, this presents an inherent problem - drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don't use sleep
.
此外, sleep
在控制方面不是很灵活。
Further, sleep
isn't very flexible when it comes to control.
对于每秒或延迟一秒运行任务,我会强烈推荐 ScheduledExecutorService
和 scheduleAtFixedRate
或 scheduleWithFixedDelay
。
For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService
and either scheduleAtFixedRate
or scheduleWithFixedDelay
.
例如,运行方法 myTask
每秒(Java 8):
For example, to run the method myTask
every second (Java 8):
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
在Java 7中:
public static void main(String[] args) {
final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
myTask();
}
}, 0, 1, TimeUnit.SECONDS);
}
private static void myTask() {
System.out.println("Running");
}
这篇关于如何延迟Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!