ptg7068951
270 HOUR 19:Creating a Threaded Program
Most statements in the application are used to create the GUI or display a
sequence of prime numbers. The following statements are used to imple-
ment threads in this program:
. Line 5: The Runnableinterface is applied to the PrimeFinderclass.
. Line 6: AThreadobject variable is created with the name gobut isn’t
assigned a value.
. Lines 41–44: If the goobject variable has a value of null, which indi-
cates the thread hasn’t been created yet, a new Threadobject is creat-
ed and stored in the variable. The thread is started by calling the
thread’s start()method, which causes the run()method of the
PrimeFinderclass to be called.
. Lines 47–60: The run()method looks for a sequence of prime num-
bers beginning with 2, displaying each one in the primestext area
component by calling its append()method. The number of primes in
the sequence is determined by the value in the howManytext field.
Working with Threads
You can starta thread by calling its start()method, which might lead
you to believe there’s also a stop()method to bring it to a halt.
Although Java includes astop()method in the Threadclass, it has been
deprecated. In Java, a deprecatedelement is a class, interface, method, or
variable that has been replaced with something that works better.
The next project you undertake shows how you can stop a thread. The pro-
gram you are writing rotates through a list of website titles and the
addresses used to visit them.
The title of each page and the web address is displayed in a continuous
cycle. Users are able to visit the currently displayed site by clicking a but-
ton on the applet window. This program operates over a period of time,
displaying information about each website in sequence. Because of this
time element, threads are the best way to control the program.
Instead of entering this program into the NetBeans source editor first and
learning about it afterward, you get a chance to enter the full text of the
LinkRotatorapplet at the end of the hour. Before then, each section of the
program is described.
CAUTION
It’s a good idea to heed this
deprecation warning. Oracle has
deprecated the stop()method
because it can cause problems
for other threads running in the
Java interpreter. The resume()
andsuspend()methods of the
class also are deprecated.