Java Reference
In-Depth Information
There are three public instance variables:
target
—A
long
that indicates when the specified prime in the sequence has been
found. If you're looking for the 5,000th prime,
target
equals 5000.
n
prime
—A
long
that holds the last prime number found by this class.
n
finished
—A Boolean that indicates when the target has been reached.
n
There is also a private instance variable called
runner
that holds the
Thread
object that
this class runs in. This object should be equal to
null
before the thread has been started.
The
PrimeFinder
constructor method in lines 7-13 sets the
target
instance variable and
starts the thread if it hasn't already been started. When the thread's
start()
method is
called, it in turn calls the
run()
method of the threaded class.
The
run()
method is in lines 15-26. This method does most of the work of the thread,
which is typical of threaded classes. You want to put the most computing-intensive tasks
in their own thread so that they don't bog down the rest of the program.
This method uses two new variables:
numPrimes
, the number of primes that have been
found, and
candidate
, the number that might possibly be prime. The
candidate
variable
begins at the first possible prime number, which is 2.
The
while
loop in lines 18-24 continues until the right number of primes has been
found.
First, it checks whether the current
candidate
is prime by calling the
isPrime(
long
)
method, which returns
true
if the number is prime and
false
otherwise.
If the
candidate
is prime,
numPrimes
increases by one, and the
prime
instance variable
is set to this prime number.
The
candidate
variable is then incremented by one, and the loop continues.
After the right number of primes has been found, the
while
loop ends, and the
finished
instance variable is set to
true
. This indicates that the
PrimeFinder
object has found the
right prime number and is finished searching.
The end of the
run()
method is reached in line 26, and the thread is no longer doing any
work.
7
The
isPrime()
method is contained in lines 28-35. This method determines whether a
number is prime by using the
%
operator, which returns the remainder of a division oper-
ation. If a number is evenly divisible by 2 or any higher number (leaving a remainder of
0), it is not a prime number.