Java Reference
In-Depth Information
Enter the text of Listing 7.3 in your Java editor and save it as PrimeFinder.java .
LISTING 7.3
The Full Text of PrimeFinder.java
1: public class PrimeFinder implements Runnable {
2: public long target;
3: public long prime;
4: public boolean finished = false;
5: private Thread runner;
6:
7: PrimeFinder(long inTarget) {
8: target = inTarget;
9: if (runner == null) {
10: runner = new Thread(this);
11: runner.start();
12: }
13: }
14:
15: public void run() {
16: long numPrimes = 0;
17: long candidate = 2;
18: while (numPrimes < target) {
19: if (isPrime(candidate)) {
20: numPrimes++;
21: prime = candidate;
22: }
23: candidate++;
24: }
25: finished = true;
26: }
27:
28: boolean isPrime(long checkNumber) {
29: double root = Math.sqrt(checkNumber);
30: for (int i = 2; i <= root; i++) {
31: if (checkNumber % i == 0)
32: return false;
33: }
34: return true;
35: }
36: }
Compile the PrimeFinder class when you're finished. This class doesn't have a main()
method, so you can't run it as an application. You create a program that uses this class
next.
The PrimeFinder class implements the Runnable interface so it can be run as a thread.
 
Search WWH ::




Custom Search