I separate the array and sum its parts separately, at the end, adding everything to a single variable using join.
class code Main
int partArray = array.length / THREAD;
int first = 0;
AtomicInteger result = new AtomicInteger(0);
Thread[] thr = new Thread[THREAD];
for(i = 0; i < THREAD; ++i) {
thr[i] = new Thread(new ThreadSum(first, first + partArray, array, result));
thr[i].start();
first += partArray;
}
for(i = 0; i < THREAD; ++i) {
thr[i].join();
}
class code Thread
int first;
int end;
private int[] array;
private AtomicInteger result;
public ThreadSum(int first, int end, int[] array, AtomicInteger result) {
this.first = first;
this.end = end;
this.array = array;
this.result = result;
}
public synchronized void run() {
int sum = 0;
for(int i = first; i < end; ++i) {
sum += array[i];
}
result.getAndAdd(sum);
}
How do I implement this without using join? Any help guys.