根据您的操作,Thread.sleep 方法可能没问题,但我仍然建议使用 ScheduledExecutorService.scheduleAtFixedRate() 方法。它已经过彻底的测试、记录和其他可能需要在未来维护您的代码的开发人员应该熟悉它。例如,它还提供取消执行和管理多个任务的方法。我会仔细看看。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.*;
public class Clock {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private boolean lastOneWasATick = false;
public void startClock() {
//Define the task
final Runnable tickTock = new Runnable() {
public void run() {
System.out.println(!lastOneWasATick ? "tick" : "tock");
lastOneWasATick = !lastOneWasATick;
}
};
//Schedule the task's execution at 1 second intervals, starting immediately
final ScheduledFuture<?> tickTockThreadHandle = scheduler.scheduleAtFixedRate(tickTock, 0, 1, SECONDS);
//Stop the clock after 1 minute
scheduler.schedule(new Runnable() {
public void run() {
tickTockThreadHandle.cancel(true);
}
}, 60, SECONDS);
}
}