/* Based on book example on page 178. */ class Sum { private int sum; // Why not a constructor this time? Start at 0. public Sum() { sum = 0; } public int getSum() { return sum; } public void setSum(int sum) { this.sum = sum; } public void addSum(int sum) { this.sum += sum; } } class Summation implements Runnable { private int upper; private Sum sumValue; public Summation(int upper, Sum sumValue) { this.upper = upper; this.sumValue = sumValue; } public void run() { int sum = 0; for (int i = 1; i <= upper; ++i) { System.out.printf("Thread 1 is adding %d\n", i); sum += i; } sumValue.addSum(sum); } } // This one will accumulate perfect squares i^2. class Summation2 implements Runnable { private int upper; private Sum sumValue; public Summation2(int upper, Sum sumValue) { this.upper = upper; this.sumValue = sumValue; } public void run() { int sum = 0; for (int i = 1; i <= upper; ++i) { System.out.printf("Thread 2 is adding %d\n", i*i); sum += i*i; } sumValue.addSum(sum); } } public class Driver { public static void main(String [] args) { if (args.length == 0) { System.err.printf("Need to include upper value as cmd line arg.\n"); System.exit(1); } int upper = Integer.parseInt(args[0]); if (upper < 0) { System.err.printf("Argument cannnot be negative.\n"); System.exit(1); } Sum sumObject = new Sum(); Thread t1 = new Thread(new Summation(upper, sumObject)); Thread t2 = new Thread(new Summation2(upper, sumObject)); t1.start(); t2.start(); try { t1.join(); t2.join(); System.out.printf("The sum for %d is %d\n", upper, sumObject.getSum()); } catch (InterruptedException e) { } } }