I need to synchronize all the threads to add all the numbers.
Threads are created, but not started immediately. When the threads do start, they must start simultaneously, without preferential treatment. That is to say, when the threads are finally allowed to start, Thread-1 should not always be the one to be scheduled on the CPU first. This should be addressed using threading constructs (mutex, semaphore, monitors, etc), and never ever managed by a call to random(), yield(), nor other convoluted equitability scheme.
Here is my code.
Threads are created, but not started immediately. When the threads do start, they must start simultaneously, without preferential treatment. That is to say, when the threads are finally allowed to start, Thread-1 should not always be the one to be scheduled on the CPU first. This should be addressed using threading constructs (mutex, semaphore, monitors, etc), and never ever managed by a call to random(), yield(), nor other convoluted equitability scheme.
Here is my code.
Code:
public class Adder {
public int[] array;
private int sum = 0;
private int index = 0;
private int number_of_threads = 10;
private int threads_quit;
static final int ARRAYSIZE = 10000;
public Adder() {
threads_quit = 0;
array = new int[ARRAYSIZE];
initializeArray();
startThreads();
}
public synchronized int getNextIndex() {
if (index < ARRAYSIZE) return (index++); else return (-1);
}
public synchronized void addPartialSum(int partial_sum) {
sum += partial_sum;
if (++threads_quit == number_of_threads)
System.out.println("The sum of the numbers is "+sum);
}
private void initializeArray() {
int i;
for (i=0; i < ARRAYSIZE ; i++) array[i] = i+1;
}
public synchronized void startThreads() {
int i = 0;
for (i=0; i< number_of_threads; i++) {
AdderThread at = new AdderThread(this,i);
at.start();
}
}
public static void main(String args[]) {
Adder a = new Adder();
}
}
class AdderThread extends Thread {
int partial_sum = 0;
Adder parent;
int number;
public AdderThread(Adder parent, int number) {
this.parent = parent;
this.number = number;
}
public synchronized void run() {
int index = 0;
index = parent.getNextIndex() ;
while (index != -1) {
partial_sum = partial_sum + parent.array[index];
index = parent.getNextIndex();
}
System.out.println("Partial sum from thread " + number + " is " +
partial_sum);
parent.addPartialSum(partial_sum);
}
}
Comment