If an applet executes a thread that is terminated only when the user closes or stops the applet, then we need to stop the thread in a different manner. This is best illustrated with an example: the ThreadForEver applet displays integers in turn starting at 1, incrementing the integer by 1, and only terminating when the user stops the applet.
ThreadForEver
import java.applet.*;
import java.awt.Graphics;
public class ThreadForEver extends Applet
implements Runnable {
Thread numbersThread;
int i = 1;
int xpos = 100;
int ypos = 50;
String text = '' ";
public void start()
{
numbersThread = new Thread(this);
numbersThread.start();
}
public void run()
{
while (numbersThread != null)
{
i++;
try
{
Thread.sleep(100);
}
catch (InterruptedException e) {}
text = Integer.toString(i);
repaint();
}
}
public void paint(Graphics g)
{
g.drawString(text, xpos, ypos);
}
public void stop()
{
numbersThread = null;
}
}
The applet implements a Runnable interface in the same manner as a finite applet thread. There is also no change to the applet start method. However, instead of a finite for loop in the run method, we specify the following while loop (line 18):
while (numbersThread != null) {
As long as the thread is not stopped, this condition will be satisfied. The run method delays execution for 100 milliseconds; this is not strictly required but is probably the minimum amount of time required to see individual integers appear on the screen. In lines 23–24, the string equivalents of the integers are displayed in the same position in the applet window using the repaint and paint methods as before.
ThreadForEver
import java.applet.*;
import java.awt.Graphics;
public class ThreadForEver extends Applet
implements Runnable {
Thread numbersThread;
int i = 1;
int xpos = 100;
int ypos = 50;
String text = '' ";
public void start()
{
numbersThread = new Thread(this);
numbersThread.start();
}
public void run()
{
while (numbersThread != null)
{
i++;
try
{
Thread.sleep(100);
}
catch (InterruptedException e) {}
text = Integer.toString(i);
repaint();
}
}
public void paint(Graphics g)
{
g.drawString(text, xpos, ypos);
}
public void stop()
{
numbersThread = null;
}
}
The applet implements a Runnable interface in the same manner as a finite applet thread. There is also no change to the applet start method. However, instead of a finite for loop in the run method, we specify the following while loop (line 18):
while (numbersThread != null) {
As long as the thread is not stopped, this condition will be satisfied. The run method delays execution for 100 milliseconds; this is not strictly required but is probably the minimum amount of time required to see individual integers appear on the screen. In lines 23–24, the string equivalents of the integers are displayed in the same position in the applet window using the repaint and paint methods as before.
No comments:
Post a Comment