Java Reference
In-Depth Information
33
Arrays.fill(primes,
true
);
// initialize all primes elements to true
34
}
35
36
// finds all primes up to max using the Sieve of Eratosthenes
37
public
Integer doInBackground()
38
{
39
int
count =
0
;
// the number of primes found
40
41
// starting at the third value, cycle through the array and put
42
// false as the value of any greater number that is a multiple
43
for
(
int
i =
2
; i < primes.length; i++)
44
{
45
if
(isCancelled())
// if calculation has been canceled
46
return
count;
47
else
48
{
49
setProgress(
100
* (i +
1
) / primes.length);
50
51
try
52
{
53
Thread.sleep(generator.nextInt(
5
));
54
}
55
catch
(InterruptedException ex)
56
{
57
statusJLabel.setText(
"Worker thread interrupted"
);
58
return
count;
59
}
60
61
if
(primes[i])
// i is prime
62
{
63
publish(i);
// make i available for display in prime list
64
++count;
65
66
for
(
int
j = i + i; j < primes.length; j += i)
67
primes[j] =
false
;
// i is not prime
68
}
69
}
70
}
71
72
return
count;
73
}
74
75
// displays published values in primes list
protected void
process(List<Integer> publishedVals)
{
for
(
int
i =
0
; i < publishedVals.size(); i++)
intermediateJTextArea.append(publishedVals.get(i) +
"\n")
;
}
76
77
78
79
80
81
82
// code to execute when doInBackground completes
83
protected void
done()
84
{
85
getPrimesJButton.setEnabled(
true
);
// enable Get Primes button
Fig. 23.26
|
Calculates the first
n
primes, displaying them as they are found. (Part 2 of 3.)