1. Write a java program using Thread to do the following: The main program initi
ID: 3753798 • Letter: 1
Question
1. Write a java program using Thread to do the following:
The main program initializes an array of size 1000 with random number between 1-10
It creates 5 threads and tell each thread to find the sum of the 200 elements and return the result
The main adds the 5 results and print the sum
2. Write a java program using Thread to do the following:
The main program initializes an array of size 1000 with values from 1-1000
Shuffle the array
Ask user to enter a number between 1 to 1000
Create 5 threads and pass the number and section of the array with 200 elements.
Each thread check to see if the number you typed is in that section of the array. If yes returns the index of the array, if not returns -1
The main print the name of the Thread
Explanation / Answer
As per chegg policy solvinf Part 1. Please ask Part 2 saperately . There will surely be an answer.
SummationTester.java
class Summation extends Thread {
private int[] arr;
private int low, high, partial;
private static int[] sumsArr;
private static Summation sums[];
public Summation(int[] arr, int low, int high) {
this.arr = arr;
this.low = low;
this.high = Math.min(high, arr.length);
}
public int getPartialSum() {
return partial;
}
public void run() {
partial = sum(arr, low, high);
}
public static int[] getPartialSumArr() {
sumsArr = new int[sums.length];
for (int i = 0; i < sums.length; i++) {
sumsArr[i] = sums[i].getPartialSum();
}
return sumsArr;
}
public static int sum(int[] arr, int low, int high) {
int total = 0;
for (int i = low; i < high; i++) {
total += arr[i];
}
return total;
}
public static void parallelSum(int[] arr) {
parallelSum(arr, 5);
}
public static void parallelSum(int[] arr, int threads) {
int size = (int) Math.ceil(arr.length * 1.0 / threads);
sums = new Summation[threads];
for (int i = 0; i < threads; i++) {
sums[i] = new Summation(arr, i * size, (i + 1) * size);
sums[i].start();
}
try {
for (Summation sum : sums) {
sum.join();
}
} catch (InterruptedException e) {
}
}
}
public class SummationTester {
public static void main(String[] args) {
Random rand = new Random();
int[] arr = new int[1000];
for (int i = 0; i < arr.length; i++) {
arr[i] = rand.nextInt(10) + 1; // 1..10
}
long start = System.currentTimeMillis();
start = System.currentTimeMillis();
Summation.parallelSum(arr);
int partialSums[] = Summation.getPartialSumArr();
int total = 0;
for (int i = 0; i < partialSums.length; i++) {
total = total + partialSums[i];
}
System.out.println("Total Sum = "+total);
System.out.println("Parallel: " + (System.currentTimeMillis() - start)+ "ms"); // Parallel:
// 25
}
}
Output
Total Sum = 5497
Parallel: 13ms
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.