对于一个简单的解决方案,你可以只使用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
我不能使用任何线程:\分配 –
如何计时器? –