Re: a tight game loop in Swing
On 06/05/2012 09:51 PM, Knute Johnson wrote:
public void run() {
try {
long now = 0;
long then = System.nanoTime();
while (true) {
render();
try {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
paintImmediately(getBounds());
}
});
} catch (InvocationTargetException ite) {
System.out.println(ite);
}
/*
while (now < then + 10000000)
now = System.nanoTime();
then = now;
*/
}
} catch (InterruptedException ie) {
System.out.println(ie);
}
}
How about this formulation?
@Override
public void run() {
for (boolean active = true; active; ) {
try {
render();
try {
EventQueue.invokeAndWait(new Runnable() {
public void run() {
paintImmediately(getBounds());
}
});
} catch (InvocationTargetException ite) {
System.out.println(ite);
}
/*
for (long pause = System.nanoTime() + 10000000L;
System.nanoTime() < pause;
) {
}
*/
} catch (InterruptedException ie) {
System.out.println(ie);
active = false;
}
}
}
I base this on vague, hence possibly superstitiously encoded memories of
Goetz's (et al.) _Java Concurrency in Practice_ and other sources.
He goes to some length to re-educate about 'InterruptedException'. I may have
got it wrong, but I seem to recall something about setting a loop condition
rather than leaping out pell-mell, and a tickle about a rethrow of the
interruption but that might be for specialized circumstances. Like when the
interruptee isn't the end of the line for handling that interrupt as it is here.
I read a book. I'm not an authority.
I loathe 'System.out' for logging. OTOH, in this case the point of the program
arguably is the exception output, so it's legit, right?
--
Lew
Honi soit qui mal y pense.
http://upload.wikimedia.org/wikipedia/commons/c/cf/Friz.jpg