I know this must have been covered in various places in the past. However, I would be interested in your opinions and alternatives for the “Applet main loop” problem; How to structure the main loop of a real-time applet?
I think we all more or less agree on:
public class RealTimeApplet extends Applet implements Runnable
{
Thread thread; // Runner thread
public void start () {
thread = new Thread ( this );
}
public void stop () {
thread = null;
}
public void run ()
{
while ( thread != null )
{
// run main loop
}
}
public void update ( Graphics g )
{ // override because origional cleared screen
paint ( g );
}
}
Now comes the interesting part. How do we update logic and then repaint in the main loop. These are some ideas/approaches I’ve seen:
- Just grab the Applet’s Graphics context and use it however you like (bypassing the paint() function). This is not very friendly, and I’m not sure have supported it is by various AWT implementations.
- In the main loop, wait() after calling repaint(). The paint() function then calls notifyAll() when it is done. When running on a fast computer, the applet can eat up too many resources (ie. freeze the system by taking almost all time). This means some performance manager must be implemented to avoid this :(.
- Just use Thread.sleep (1L) at the end of the main loop. This is kind of a hack :(. It avoids eating too many resources though.
I would like to know what other approaches there are, because these all have some drawback(s) which I don’t like.
Also, who uses ToolKit.vsync () and where should it be used. Who uses Thread.yield () and where should it be used.
You see I have many questions ;). Sorry guys, but I’m looking to sort this out once and for all.
Thanks.
from, Stefan