Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Starting the Thread 275

currentThread(), sets up the value for the thisThreadobject. The
currentThread()method keeps track of the thread that’s currently running.


All statements in this method are part of a whileloop that compares the
runnerobject to the thisThreadobject. Both objects are threads, and as
long as they refer to the same object, the whileloop continues looping.
There’s no statement inside this loop that causes the runnerand
thisThreadobjects to have different values, so it loops indefinitely unless
something outside of the loop changes one of the Threadobjects.


The run()method calls repaint(). Next, the value of the currentvariable
increases by one, and if currentexceeds 5, it is set to 0 again. The current
variable is used in the paint()method to determine which website’s infor-
mation to display. Changing currentcauses a different site to be displayed
the next time paint()is handled.


This method includes another try-catchblock that handles errors. The
Thread.sleep(10000)statement causes a thread to pause 10 seconds, long
enough for users to read the name of the website and its address. The
catchstatement takes care of any InterruptedExceptionerrors that might
occur while the Thread.sleep()statement is being handled. These errors
would occur if something interrupted the thread as it slept.


Stopping the Thread


The stop()method is called any time the applet is stopped because the
applet’s page is exited, which makes it an ideal place to stop a running
thread. The stop()method for the LinkRotatorapplet contains the fol-
lowing statements:


public voidstop() {
if (runner!= null) {
runner= null;
}
}


The ifstatement tests whether the runnerobject is equal to null. If it is,
there isn’t an active thread that needs to be stopped. Otherwise, the state-
ment sets runnerequal to null.


Setting the runnerobject to a nullvalue causes it to have a different value
than the thisThreadobject. When this happens, the whileloop inside the
run()method stops running.

Free download pdf