/** * Copyright (c): Uwe Schmidt, FH Wedel * * You may study, modify and distribute this source code * FOR NON-COMMERCIAL PURPOSES ONLY. * This copyright message has to remain unchanged. * * Note that this document is provided 'as is', * WITHOUT WARRANTY of any kind either expressed or implied. */ public class CountPrimes extends Thread { long lb, ub; long max; int noOfPrimes; CountPrimes child; public CountPrimes(long lb, long ub, long max) { super("CountPrimes(" + lb + "," + ub + ")"); System.out.println("creating thread " + getName()); this.lb = lb; this.ub = ub; this.max = max; splitWorkload(); } public void run() { System.out.println(getName() + " is running"); startChild(); doOwnWork(); waitForChild(); System.out.println(getName() + " has finished"); } private void splitWorkload() { if (ub - lb > max) { long splitAt = lb + max; child = new CountPrimes(splitAt, ub, max); ub = splitAt; } else { child = null; } } private void startChild() { if (child != null) { child.start(); } } private void doOwnWork() { System.out.println(getName() + " is working"); for (long i = lb; i < ub; ++i) { if (isPrime(i)) ++noOfPrimes; } System.out.println(getName() + " has done own work"); } private void waitForChild() { if (child != null) { System.out.println(getName() + " is waiting for child"); try { child.join(); } catch (InterruptedException e) { } System.out.println(getName() + " child has joined"); noOfPrimes += child.noOfPrimes; } } private boolean isPrime(long n) { long i = 2; if (n <= 1) return false; while ( n % i != 0 && i * i <= n) ++i; return i * i > n; } }