Java Reference
In-Depth Information
Listing 7.4 contains an application that uses the PrimeFinder class. Enter the text of
Listing 7.4 and save the file as PrimeThreads.java .
LISTING 7.4
The Full Text of PrimeThreads.java
1: public class PrimeThreads {
2: public static void main(String[] arguments) {
3: PrimeThreads pt = new PrimeThreads(arguments);
4: }
5:
6: public PrimeThreads(String[] arguments) {
7: PrimeFinder[] finder = new PrimeFinder[arguments.length];
8: for (int i = 0; i < arguments.length; i++) {
9: try {
10: long count = Long.parseLong(arguments[i]);
11: finder[i] = new PrimeFinder(count);
12: System.out.println(“Looking for prime “ + count);
13: } catch (NumberFormatException nfe) {
14: System.out.println(“Error: “ + nfe.getMessage());
15: }
16: }
17: boolean complete = false;
18: while (!complete) {
19: complete = true;
20: for (int j = 0; j < finder.length; j++) {
21: if (finder[j] == null) continue;
22: if (!finder[j].finished) {
23: complete = false;
24: } else {
25: displayResult(finder[j]);
26: finder[j] = null;
27: }
28: }
29: try {
30: Thread.sleep(1000);
31: } catch (InterruptedException ie) {
32: // do nothing
33: }
34: }
35: }
36:
37: private void displayResult(PrimeFinder finder) {
38: System.out.println(“Prime “ + finder.target
39: + “ is “ + finder.prime);
40: }
41: }
Save and compile the file when you're finished.
 
Search WWH ::




Custom Search