I'm trying to write some code in java that uses a variable number 'p' of threads to calculate the average of elements in an array.
I created this class to represent each thread:
class Worker extends Thread {
int[] a;
int low;
int upp;
double avg = 0;
public Worker(int[] a, int low, int upp){
this.a = a;
this.low = low;
this.upp = upp;
}
public void run(){
int sum = 0;
for (int i = low; i < upp; i++){
sum+=a[i];
}
avg = (double)sum/a.length;
}
}
And this is the code to calculate the average:
static double parallelaverage(int a[], int p) {
int avg = 0;
int num = a.length/p;
ArrayList<Worker> threads = new ArrayList<Worker>();
for (int i = 0; i<a.length; i+=num){
if (i+num > a.length){
Worker x = new Worker(a, i, a.length);
x.start();
threads.add(x);
}
else{
Worker x = new Worker(a, i, i+num);
x.start();
threads.add(x);
}
}
try{for (Worker thread: threads){
thread.join();}
} catch (Exception e){}
for (Worker thread: threads){
avg += thread.avg;
}
return avg;
}
This seems to make sense to me, but the actual result I get is always way off what would be the actual average. What's wrong with my code?