/* PrimeCounter.java * Use Java threading to count the number of prime * numbers between 0 and a large number N * Compare the timing of using 2 threads vs * using just one thread. * * The load balancing is not great in this version * * javac PrimeCounter.java * java PrimeCounter */ public class PrimeCounter implements Runnable { private int start; private int extent; private int count; public PrimeCounter (int s, int e) { start = s; extent = e; count = 0; } public boolean is_prime (int n) { if (n < 2) return false; if (n == 2) return true; if (n%2 == 0) return false; for (int i = 3; i < n; i += 2) { if (n % i == 0) return false; } return true; } public void run () { for (int i = start; i < start + extent; i++) { if (is_prime(i)) { count += 1; } } } public int count () { return count; } public static void main (String args[]) { int N = 1000000; PrimeCounter pc1 = new PrimeCounter(0, N/2); PrimeCounter pc2 = new PrimeCounter(N/2, N/2); PrimeCounter pc3 = new PrimeCounter(0, N); Thread t1 = new Thread(pc1); Thread t2 = new Thread(pc2); Thread t3 = new Thread(pc3); long start = System.currentTimeMillis(); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (Exception e) { System.err.println(e); } int count = pc1.count() + pc2.count(); long end = System.currentTimeMillis(); System.out.printf("Two threads count %d primes in %d ms\n", count, end-start); // Time sequential solution, but using 1 thread start = System.currentTimeMillis(); t3.start(); try { t3.join(); } catch (Exception e) { System.err.println(e); } count = pc3.count(); end = System.currentTimeMillis(); System.out.printf("One threads count %d primes in %d ms\n", count, end-start); } }