これも昔書いたと思ってたけど無かったので
自分用メモ書き。
public static long beforeTime, afterTime, timeDiff, sleepTime;
public static long PERIOD = 10L;
public static boolean next = false;
public class Animation extends Thread {
@Override
public void run() {
long overSleepTime = 0L;
int noDelays = 0;
while (true) {
beforeTime = System.nanoTime();
next = false;
//いろいろ処理
repaint();
//repaint()の終了時に、nextをtrueにする。
try {
while (!next) {
Thread.sleep(1);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (PERIOD * 1000000L - timeDiff) - overSleepTime;
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime / 1000000L);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
} else {
overSleepTime = 0L;
if (++noDelays >= 16) {
Thread.yield();
noDelays = 0;
}
}
}
}
}
自分用メモ書き。
public static long beforeTime, afterTime, timeDiff, sleepTime;
public static long PERIOD = 10L;
public static boolean next = false;
public class Animation extends Thread {
@Override
public void run() {
long overSleepTime = 0L;
int noDelays = 0;
while (true) {
beforeTime = System.nanoTime();
next = false;
//いろいろ処理
repaint();
//repaint()の終了時に、nextをtrueにする。
try {
while (!next) {
Thread.sleep(1);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (PERIOD * 1000000L - timeDiff) - overSleepTime;
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime / 1000000L);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
} else {
overSleepTime = 0L;
if (++noDelays >= 16) {
Thread.yield();
noDelays = 0;
}
}
}
}
}