/* PrimeCounterBetterLoad.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 PrimeCounterBetterLoad implements Runnable { private int start; private int small_extent; private int big_stride; private int N; private int count; public PrimeCounterBetterLoad (int s, int se, int bs, int N) { start = s; small_extent = se; big_stride = bs; this.N = N; 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 < this.N; i = i + big_stride) { for (int j = 0; j < small_extent; j++) { if (is_prime(i+j)) count += 1; } } } public int count () { return count; } public static void main (String args[]) { int N = 1000000; int small_extent = 100; int NUM_THREADS = 2; int big_stride = NUM_THREADS * small_extent; PrimeCounterBetterLoad pc1 = new PrimeCounterBetterLoad(0, small_extent, big_stride, N); PrimeCounterBetterLoad pc2 = new PrimeCounterBetterLoad(small_extent, small_extent, big_stride, N); PrimeCounterBetterLoad pc3 = new PrimeCounterBetterLoad(0, N, N, 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); } }