// Sum3.java class SumThread extends Thread { private int from, to, sum; public SumThread(int from, int to) { this.from = from; this.to = to; sum = 0; } @Override public void run() { for (int i = from; i <= to; i++) { sum += i; } } public int getSum() { return sum; } } public class Sum3 { 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]); int from = Integer.parseInt(args[1]); int to = Integer.parseInt(args[2]); // an array of threads SumThread [] threads = new SumThread[num_threads]; // fill in the start/end ranges for each int step = (to - from) / num_threads; for (int i = 0; i < num_threads; i++) { int start = from + step * i; int stop = (start + step) - 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 %d sums from %d to %d.\n", i, start, stop); 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 int total_sum = 0; for (int i = 0; i < num_threads; i++) { total_sum += threads[i].getSum(); } System.out.printf("The sum of %d-%d is %d.\n", from, to, total_sum); } }