// Sum4.java import java.math.BigInteger; class SumThread extends Thread { private BigInteger from, to, sum; public SumThread(BigInteger from, BigInteger to) { this.from = from; this.to = to; sum = new BigInteger("0"); } @Override public void run() { BigInteger one = new BigInteger("1"); for (BigInteger i = from; i.compareTo(to) <= 0; i = i.add(one)) { sum = sum.add(i); } } public BigInteger getSum() { return sum; } } public class Sum4 { public static void main(String args[]) { if (args.length != 3) { System.out.println("Pass threads, start and end."); return; } // get arguments int num_threads = Integer.parseInt(args[0]); BigInteger from = new BigInteger(args[1]); BigInteger to = new BigInteger(args[2]); // an array of threads SumThread [] threads = new SumThread[num_threads]; // fill in the start/end ranges for each BigInteger step = to.subtract(from).divide(BigInteger.valueOf(num_threads)); for (int i = 0; i< num_threads; i++) { BigInteger start = from.add(step.multiply(BigInteger.valueOf(i))); BigInteger stop = start.add(step).subtract(BigInteger.valueOf(1)); // make sure we go all the way to the end on last thread if (i == (num_threads - 1)) { stop = to; } System.out.printf("Thread %s sums from %s to %s.\n", i, start.toString(), stop.toString()); threads[i] = new SumThread(start, stop); } // start them all for (int i = 0; i< num_threads; i++) { threads[i].start(); } // wait for all the threads to finish! try { for (int i = 0; i< num_threads; i++) { threads[i].join(); } } catch (InterruptedException e) { System.out.println("Interrupted"); } // calculate total sum BigInteger total_sum = new BigInteger("0"); for (int i = 0; i < num_threads; i++) { total_sum = total_sum.add(threads[i].getSum()); } System.out.printf("The sum of %s-%s is %s.\n", from.toString(), to.toString(), total_sum.toString()); } }