If you want faster execution using Threads, I think that you should use a single class that will accomplish the same thing as serial, something like that :
public class Calc extends Thread {
private int[] array;
private double sum;
public Calc(int[] array) {
this.array = array;
this.sum = 0;
}
@Override
public void run() {
for (int i = 0; i < array.length; i++) {
sum += Math.sqrt(array[i]);
}
}
public double getSum() {
return this.sum;
}
}
In this way, parallel computing is 2 times faster than serial coputing. I think the pattern Producer-Consummer you applied can't be faster than serial because you make way more instructions and breaks in the code by :
- Getting a new value (Consumer waits a new item to be available)
- Using this value (Producer waits consummer to finish its calculation)
Maybe the producer should be the one who generates random number, and the consummer the one using these values ?
(And please use while(isRead)
and !
operator for the contrary instead of those ugly while(isRead == false)
: this is more readable ;))