對於一個簡單的解決方案,你可以只使用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週期,其他兩種解決方案的代價就會很高,其中就是這樣和Timer
使用內部調度機制,允許線程空閒(並且不消耗週期)
'Thread.sleep(pause)'...? – MadProgrammer
我不能使用任何線程:\分配 –
如何計時器? –