I have a Java program that uses threads. In my run method, I have:
public void run() {
while(thread != null){
repaint();
System.out.print
Depending on what you're doing, you might also be interested in this. This is taken from Killer Game Programming in Java by Andrew Davison. He talks about active rendering. Your game loop is effectively:
public void run()
{
while (running)
{
gameUpdate(); // game state is updated
gameRender(); // render to a buffer
paintScreen(); // draw buffer to screen
try
{
Thread.sleep(20);
}
catch (InterruptedException e) {;}
}
}
And, the implementation of paint screen is (defined by a subclass of JComponent):
private void paintScreen()
{
final Graphics2D g2d;
try
{
g2d = (Graphics2D) this.getGraphics();
if (g2d != null && (backbuffer != null))
{
g2d.drawImage(backbuffer, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync(); // sync the display on some systems [1]
g2d.dispose();
}
catch (Exception e)
{
;
}
}
From the book:
[Note 1] The call to
Tookkit.sync()ensures that the display is promptly updated. This is required for Linux, which doesn't automatically flush its display buffer. Without thesync()call, the animation may be only partially updated, creating a "tearing" effect.