簡単な解決策として、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サイクルを消費し続けるため、これは他の2つのソリューションよりもコストがかかることに注意してください。一方、スレッドがアイドル状態になる(サイクルを消費しない)内部スケジューリングメカニズムThread#sleep
をTimer
使用する