Optimize the two threads and how drawing is handled.

This commit is contained in:
Jan Philipp Timme 2014-10-24 23:22:26 +02:00
parent a733187887
commit f26c9366cd
5 changed files with 18 additions and 14 deletions

View File

@ -39,9 +39,12 @@ public class GameFrame extends JFrame {
this.setVisible(true);
//ignore the OS telling us to repaint - it's wasting our time.
this.setIgnoreRepaint(true);
//prepare the buffered strategy
this.createBufferStrategy(2);
this.bufferStrategy = this.getBufferStrategy();
}
/**
@ -71,7 +74,7 @@ public class GameFrame extends JFrame {
} while (this.bufferStrategy.contentsRestored());
this.bufferStrategy.show();
} while (this.bufferStrategy.contentsLost());
Toolkit.getDefaultToolkit().sync();
Toolkit.getDefaultToolkit().sync(); //Tell the OS to update its graphics of the window.
}
public void drawBackgrounds(Graphics g) {

View File

@ -13,7 +13,7 @@ public class PaintThread extends TimingThread {
public PaintThread(GameFrame gf) {
this.gf = gf;
this.setName("GameThread");
this.setName("PaintThread");
this.setHz(60);
}

View File

@ -19,11 +19,10 @@ public abstract class TimingThread extends Thread {
public void run() {
while (true) {
long workStart = System.nanoTime();
// do the actual work
this.work();
long workDone = System.nanoTime();
//calculate time of work
long workTime = (workDone - workStart);
long timeToWait = this.workInterval - workTime;
@ -32,14 +31,16 @@ public abstract class TimingThread extends Thread {
// wait using sleep for bigger intervals
if (msToWait > 1) {
try {
Thread.sleep(msToWait);
//make sure there is a little buffer for manual waiting loop left
Thread.sleep(Math.max(0,(msToWait - 1)));
} catch (InterruptedException e) {
System.err.println("[" + this.getName() + "]" + e.getStackTrace());
}
}
while (this.workInterval - (System.nanoTime() - workStart) > 100);
//System.out.println("[" + this.getName() + "]: "+ (System.nanoTime() - workStart));
//wait manually for the rest of the interval
long sleepUntil = workStart + this.workInterval;
while ((sleepUntil- System.nanoTime()) > 100);
}
}

View File

@ -9,13 +9,13 @@ public class UpdateThread extends TimingThread {
public UpdateThread() {
this.setName("UpdateThread");
this.setHz(100);
this.setHz(60);
}
public void work() {
// Update all the entities
this.updateBackgrounds();
this.updateEntities();
// Update all the entities
this.updateBackgrounds();
this.updateEntities();
}
private void updateBackgrounds() {