If you want to pause then use java.util.concurrent.TimeUnit
:
(如果要暂停,请使用java.util.concurrent.TimeUnit
:)
TimeUnit.SECONDS.sleep(1);
To sleep for one second or
(睡一秒钟或)
TimeUnit.MINUTES.sleep(1);
To sleep for a minute.
(睡一分钟。)
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.
(此外,就控制而言, sleep
不是很灵活。)
For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService
and either scheduleAtFixedRate
or scheduleWithFixedDelay
.
(为了每秒运行一次任务或延迟一秒钟,我强烈建议您使用ScheduledExecutorService
以及scheduleAtFixedRate
或scheduleWithFixedDelay
。)
For example, to run the method myTask
every second (Java 8):
(例如,要myTask
运行方法myTask
(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");
}
And in Java 7:
(在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");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…