To eksempler som viser forskel paa sleep loop og real timer:
public class SleepLoop {
private static void dosomething() throws InterruptedException {
// simulate that it takes some time
Thread.sleep(100);
}
public static void main(String[] args) throws InterruptedException {
long t = System.currentTimeMillis();
while(true) {
dosomething();
Thread.sleep(1000);
long t2 = System.currentTimeMillis();
System.out.printf("%5.3f seconds\n", (t2 - t)/1000.0);
t = t2;
}
}
}
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class RealTimer {
public static void main(String[] args) throws IOException {
Timer timer = new Timer();
timer.schedule(new DoSomethingTask(), 1000, 1000);
System.in.read();
timer.cancel();
}
}
class DoSomethingTask extends TimerTask {
private long t;
public DoSomethingTask() {
t = System.currentTimeMillis();
}
private static void dosomething() throws InterruptedException {
// simulate that it takes some time
Thread.sleep(100);
}
public void run() {
try {
dosomething();
} catch (InterruptedException e) {
e.printStackTrace();
}
long t2 = System.currentTimeMillis();
System.out.printf("%5.3f seconds\n", (t2 - t)/1000.0);
t = t2;
}
}