In: Computer Science
Write an application that uses multithreading to compute the sum of the integers in an array of size 100,000. You can populate the array with random numbers and your application should display the sum. (JAVA)
Program Screenshots:
Sample Output:
Code to be Copied:
DriverProgram.java
//import required package
import java.util.Random;
// Application driver code to compute sum
public class DriverProgram
{
//declare local variable
public static final int SIZE = 100000;
//main method
public static void main(String[] args)
{
//create object for random
Random r = new Random();
//create array of size
int[] array = new int[SIZE];
//use for loop to create random
numbers
for (int i = 0; i <
array.length; i++)
{
array[i] =
r.nextInt(100001) + 1;
}
//call the method in the mutithread
class
long arraySum=
MultiThreading.multiThreadSum(array);
//print the result
System.out.println("Array sum using
MultiThreading is: " + arraySum);
}
}
MultiThreading.java
//Create class Application which extends thread
public class MultiThreading extends Thread
{
//Declare 8 threads
public static final int NUM_THREADS = 10;
private int[] array;
private int start, end, sum;
//create constructor for the class
public MultiThreading(int[] inputarr, int l, int
h)
{
this.array = inputarr;
this.start = l;
this.end = Math.min(h,
inputarr.length);
}
//implement run method
//to invoke when thread starts
public void run()
{
//call the other method to compute
the sum
//for each thred
sum = eachThreadSum(array, start,
end);
}
//Implement method sum to compute
eachThreadSum
public static int eachThreadSum(int[] arr, int low,
int high)
{
//declare variable
int total = 0;
//use for-loop to compute the
total
for (int i = low; i < high;
i++)
{
total +=
arr[i];
}
//return total
return total;
}
//implement method to compute sum for
multithreads
public static int multiThreadSum(int[] arr)
{
//call sub method for the array and
numthreads
return multiThreadSum(arr,
NUM_THREADS);
}
//implement method to compute sum
public static int multiThreadSum (int[] arr, int
threads)
{
//get the size of the array of each
thread
int size = (int)
Math.ceil(arr.length * 1.0 / threads);
MultiThreading[] threadSum = new
MultiThreading[threads];
//use for-loop to compute
sum
for (int i = 0; i < threads;
i++)
{
threadSum[i] =
new MultiThreading(arr, i * size, (i + 1) * size);
//invoke start
method to implement run method
threadSum[i].start();
}
//join each thread
try
{
for
(MultiThreading sum : threadSum)
{
sum.join();
}
}
//if the sum is not
calculated
//throw exception contains
message
catch (InterruptedException
e)
{
e.getMessage();
}
//compute sum by calling
method
int total = 0;
for (MultiThreading sum :
threadSum)
{
total +=
sum.getPartialSum();
}
//return total
return total;
}
//accessor method
public int getPartialSum()
{
return sum;
}
}