对于一个简单的解决方案,您可以使用Thread#sleep
public void waitForExecution(long pause) throws InterruptedException {
// Perform some actions...
Thread.sleep(pause);
// Perform next set of actions
}
用计时器...
public class TimerTest {
public static void main(String[] args) {
Timer timer = new Timer("Happy", false);
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("Hello, I'm from the future!");
}
}, 5000);
System.out.println("Hello, I'm from the present");
}
}
并带有一个循环
long startAt = System.currentTimeMillis();
long pause = 5000;
System.out.println(DateFormat.getTimeInstance().format(new Date()));
while ((startAt + pause) > System.currentTimeMillis()) {
// Waiting...
}
System.out.println(DateFormat.getTimeInstance().format(new Date()));
请注意,这比其他两个解决方案更昂贵,因为循环继续消耗 CPU 周期,其中Thread#sleep
并Timer
使用允许线程空闲(而不消耗周期)的内部调度机制