Java Reference
In-Depth Information
The PrimeThreads application can be used to find one or more prime numbers in
sequence. Specify the prime numbers that you're looking for as command-line arguments
and include as many as you want.
If you're using the JDK, here's an example of how you can run the application:
java PrimeThreads 1 10 100 1000
This produces the following output:
Looking for prime 1
Looking for prime 10
Looking for prime 100
Looking for prime 1000
Prime 1 is 2
Prime 10 is 29
Prime 100 is 541
Prime 1000 is 7919
The for loop in lines 8-16 of the PrimeThreads application creates one PrimeFinder
object for each command-line argument specified when the program is run.
Because arguments are Strings and the PrimeFinder constructor requires long values,
the Long.parseLong( String ) class method is used to handle the conversion. All the
number-parsing methods throw NumberFormatException exceptions, so they are
enclosed in try - catch blocks to deal with arguments that are not numeric.
When a PrimeFinder object is created, the object starts running in its own thread (as
specified in the PrimeFinder constructor).
The while loop in lines 18-34 checks to see whether any PrimeFinder thread has com-
pleted, which is indicated by its finished instance variable equaling true . When a
thread has completed, the displayResult() method is called in line 25 to display the
prime number that was found. The thread then is set to null , freeing the object for
garbage collection (and preventing its result from being displayed more than once).
The call to Thread.sleep(1000) in line 30 causes the while loop to pause for 1 second
during each pass through the loop. A slowdown in loops helps keep the Java interpreter
from executing statements at such a furious pace that it becomes bogged down.
Stopping a Thread
Stopping a thread is a little more complicated than starting one. The Thread class
includes a stop() method that can be called to stop a thread, but it creates instabilities in
Java's runtime environment and can introduce hard-to-detect errors into a program. For
this reason, the method has been deprecated, indicating that it should not be used in favor
of another technique.
7
Search WWH ::




Custom Search