Write a program called SumArray that uses n threads to add the contents of an ar
ID: 3863445 • Letter: W
Question
Write a program called SumArray that uses n threads to add the contents of an array of 1,000,000 random integers. You can assume that n > 1. The first thread should add up the first 1/n^th of the array, the second thread should add up the next 1/n^th of the array and so on. Use the join operation to wait for all threads to finish before printing out the final result. Write an AdderThread class (that extends Thread) to do the actually adding work. Adder Thread's constructor should accept (as parameters) the array of integers and two integers (lo and hi) representing the starting and ending indexes for its portion of the array. The AdderThread class should also contain a static method addEm (called by the test driver) that takes the array and n (number of threads) as parameters. This method should spawn off n threads, each given a chunk of the array to work on. It then waits for all threads to finish (using join) before returning the final sum. To ensure that other threads get an opportunity to run, each thread should call yield (or sleep) every so often to relinquish the CPU. Inside the loop that does the actual addition for the thread, add code so there is a 25% chance of yielding (pick a random floating point value and if its below 0.25, then yield). In reality, this would be a bad idea for performance reasons (choosing a random number takes far more CPU time than adding integers), but we're focused on experimentation with threads and not just on performance.Explanation / Answer
CODE:
package temp;
import java.util.Random;
// AdderThread class extends Thread Class.
class AdderThread extends Thread{
private int[] integerArray;
private int low;
private int high;
private int sum;
// Constructor accepting array, low and high values.
public AdderThread(int[] integerArray, int low, int high) {
this.integerArray = integerArray;
this.low = low;
this.high = high;
}
// getSum will returns sum
public int getSum() {
return sum;
}
// run method will calculate the sum
public void run() {
try {
this.sum = sumRange(integerArray, low, high);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// calculates the sum based on the low and high range of the input array.
private int sumRange(int[] a, int min, int max) throws InterruptedException {
int result = 0;
// generate random number and sleep for 50ms
// if random number is greater than 0.25
double yieldNum = Math.random();
if(yieldNum > 0.25)
Thread.sleep(50);
for (int i = min; i < max; i++) {
result += a[i];
}
return result;
}
// static method addEm will spawn the threads.
public static int addEm(int[] a, int threadCount){
// calculate the length
int len = (int) Math.ceil(1.0 * a.length / threadCount);
// create an array of threads based on thread count.
AdderThread[] summers = new AdderThread[threadCount];
Thread[] threads = new Thread[threadCount];
// spawn the threads
for (int i = 0; i < threadCount; i++) {
summers[i] = new AdderThread(a, i*len, Math.min((i+1)*len, a.length));
threads[i] = new Thread(summers[i]);
threads[i].start();
}
// wait for all the threads to complete
try {
for (Thread t : threads) {
t.join();
}
} catch (InterruptedException ie) {}
// calculate the final sum.
int total = 0;
for (AdderThread summer : summers) {
total += summer.getSum();
}
return total;
}
}
// SumArray class
public class SumArray {
private static final Random RAND = new Random(42); // random number generator
// Creates an array of the given length, fills it with random
// non-negative integers, and returns it.
public static int[] createRandomArray(int length) {
int[] a = new int[length];
for (int i = 0; i < a.length; i++) {
a[i] = RAND.nextInt(50);
}
return a;
}
public static void main(String[] args) throws Throwable {
// LENGTH to indicate the count of numbers to sum.
int LENGTH = 1000;
// generate the number array.
int[] a = createRandomArray(LENGTH);
int total = 0;
// using 4 threads
total = AdderThread.addEm(a, 4);
System.out.println("Sum of the numbers is: " + total);
}
}
OUTPUT:
Sum of the numbers is: 25170
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.