1public class CountPrimes
2 extends Thread {
3
4 long lb, ub;
5 long max;
6 int noOfPrimes;
7
8 CountPrimes child;
9
10 public CountPrimes(long lb, long ub, long max) {
11 super("CountPrimes(" + lb + "," + ub + ")");
12
13 System.out.println("creating thread " + getName());
14
15 this.lb = lb;
16 this.ub = ub;
17 this.max = max;
18
19 splitWorkload();
20 }
21
22 public void run() {
23 System.out.println(getName() + " is running");
24
25 startChild();
26 doOwnWork();
27 waitForChild();
28
29 System.out.println(getName() + " has finished");
30 }
31
32 private void splitWorkload() {
33 if (ub - lb > max) {
34
35 long splitAt = lb + max;
36
37 child = new CountPrimes(splitAt, ub, max);
38
39 ub = splitAt;
40 } else {
41 child = null;
42 }
43 }
44
45 private void startChild() {
46 if (child != null) {
47 child.start();
48 }
49 }
50
51 private void doOwnWork() {
52 System.out.println(getName() + " is working");
53
54
55 for (long i = lb; i < ub; ++i) {
56 if (isPrime(i))
57 ++noOfPrimes;
58 }
59
60 System.out.println(getName() + " has done own work");
61 }
62
63 private void waitForChild() {
64 if (child != null) {
65 System.out.println(getName() + " is waiting for child");
66
67 try {
68 child.join();
69 }
70 catch (InterruptedException e) {
71 }
72
73 System.out.println(getName() + " child has joined");
74
75 noOfPrimes += child.noOfPrimes;
76 }
77 }
78
79 private boolean isPrime(long n) {
80 long i = 2;
81 if (n <= 1)
82 return false;
83
84 while ( n % i != 0 && i * i <= n)
85 ++i;
86
87 return i * i > n;
88 }
89}