ptg7068951
274 HOUR 19:Creating a Threaded Program
Starting the Thread
In this applet, the runnerthread starts when the applet’s start()method
is called and stop when its stop()method is called.
The start()method is called right after the init()method and every
time the program is restarted. Here’s the method:
public voidstart() {
if (runner== null) {
runner= newThread(this);
runner.start();
}
}
This method starts the runnerthread if it is not already started.
The statement runner = new Thread(this)creates a new Threadobject
with one argument—the thiskeyword. The thiskeyword refers to the
applet itself, designating it as the class that runs within the thread.
The call to runner.start() causes the thread to begin running. When a
thread begins, the run()method of that thread is called. Because the run-
nerthread is the applet itself, the run()method of the applet is called.
Running the Thread
Therun()method is where the main work of a thread takes place. In the
LinkRotatorapplet, the following represents the run()method:
public voidrun() {
Thread thisThread = Thread.currentThread();
while(runner== thisThread) {
current++;
if (current> 5) {
current= 0;
}
repaint();
try {
Thread.sleep(10000);
} catch(InterruptedException e) {
// do nothing
}
}
}
The first thing that takes place in the run()method is the creation of a
Threadobject called thisThread. A class method of the Threadclass,