Home E-Books Special Effects and Game Development in Java The run() method 

Special Effects and Game Development in Java(TM) - The run() method 

by Anibal Wainstein

3.0.2 The run() method 

In contrast to the start() and stop() methods, the run() method will always be different from applet to applet. This methods is always called by your self-created thread. This means that you have a thread that works with the applets other methods (the main thread) and a thread that works with the run() method (your own thread that you initialize in the start() method). By "holding" the thread in the run() method with a loop, you can exploit it to do work that will not hang the JVM: 

public void run()
{
    while (true)
    {
   
   }
}
In the example above we are holding the thread within the loop forever (or until the applet's stop() method is called). The problem with the applet that we made in chapter 2.0.4, was that it was overwritten by other status messages from the web browser. Threads can help us here, because they constantly manage to update a message on the status window, and by doing so, overwriting other web browser messages. Let us rewrite the applet: 
import java.applet.*;
import java.awt.*; public class threadtest extends Applet implements Runnable { public Thread animationthread = null; public void start() { if (animationthread == null) { animationthread = new Thread(this,"animationthread"); animationthread.start(); } } public void stop() { if ((animationthread != null) && animationthread.isAlive()) animationthread.stop(); animationthread = null; } public void run() { while (true) { showStatus("Hello Sweden!"); } } } 
Compile the applet and run it. You can also click here to see it. You will notice that the message "Hello Sweden!" is being displayed in the status window of your browser.

 

 


Next Page >>