// // Simple program demonstrating the use of threads to // sum the integers 1 through N. // // Command-line arguments are N and P (number of threads). // // "import" statements are (sort of) analogous to C++ #include import java.text.*; // has NumberFormat // ---- class containing main program -------------------------------- public class ThreadsSum1 { public static void main(String[] args) { if (args.length < 2) { System.err.println("Usage: java ThreadsSum1 " + "highestNum numThreads"); System.exit(1); } int N = Integer.parseInt(args[0]); int P = Integer.parseInt(args[1]); System.out.println("Summing the first " + N + " positive integers using " + P + " threads:"); double startTime = ThreadsTimer.elapsedSeconds(); // Create threads. Thread[] threads = new Thread[P]; for (int i = 0; i < P; i++) { threads[i] = new Thread(new SumThreadObj(i, P, N)); } // Initialize sum. SumThreadObj.sum = 0.0; // Start up the threads. for (int i = 0; i < P; i++) { threads[i].start(); } // Wait for them to finish. for (int i = 0; i < P; i++) { try { threads[i].join(); } catch (InterruptedException e) { } } // Print result. NumberFormat nf = NumberFormat.getInstance(); // set up to print "sum" in fixed-point // (not exponential) integer format. nf.setMaximumFractionDigits(0); System.out.println("Sum = " + nf.format(SumThreadObj.sum)); double endTime = ThreadsTimer.elapsedSeconds(); System.out.println("Elapsed time (seconds) = " + ThreadsTimer.format(endTime - startTime)); } } // ---- class for threads -------------------------------------------- // We'll have one object of this class for each thread. // It holds the data needed by the thread, plus the code. class SumThreadObj implements Runnable { // Class variable (like C++ static member variable). // (This is shared by all instances of the class.) public static double sum; // Instance variables (like C++ member variables). private int id, p, n; // Constructor. public SumThreadObj(int id, int p, int n) { this.id = id; this.p = p; this.n = n; } // Instance methods (like C++ member functions). // This method implements run() in the Runnable interface // to define the behavior of a thread using this object. // It computes partial sum of n/p of the elements (starting // with id+1 and summing every p-th element) and adds // it to the sum. public void run() { double partialSum = 0.0; for (int i = id+1; i <= n; i+=p) partialSum += i; addPartialSum(partialSum); } // This method adds a partial sum to "sum". It's static and // synchronized so only one thread at a time can modify "sum"). private static synchronized void addPartialSum(double partSum) { sum += partSum; } }