mercredi 29 juin 2016

Using Threads to sum numbers from a vector

I dont think im understand Threads as i should be. Im trying to make a very redundant app in android that gets user input(Numbers) and stores them inside a vector. From that vector i start 7 Threads that should sum up all the numbers from that vector in whatever random order and when its done should Log the output. But what im getting is 7 Threads each summing up everything by itself... So im probably not using wait() and notifyAll() correctly.

I have 2 classes that extends Thread:

MasterThread:

 public MasterThread(int M,String nums){
    SumArray = new SumThread[M];
    SumVector = new Vector<>();
    SumString(nums);
}

@Override
public synchronized void run(){
    for (int i = 0; i <7 ; i++) {
        SumArray[i] = new SumThread(this);
        SumArray[i].start();
    }
}

From what i understand each Thread get its own 'this' and so every Thread gets its own vector, but i did make SumVector a static variable so i hoped it would use that one only.

The more important class is the SumThread:

public void run(){
    first = getRandom(m.SumVector);
    second = getRandom(m.SumVector);
    sumit(first, second);
    m.SumVector.add(first+second);
    while (m.SumVector.size() > 1) {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    Log.d("Output:", m.SumVector.toString());
}

private synchronized void sumit(int f, int s){
    m.SumVector.removeElement(f);
    m.SumVector.removeElement(s);
    notifyAll();
}

Which is where im probabaly doing something wrong.

I thought that each SumThread gets the same Vector from MasterThread, so i get two random numbers from the vector and then i remove them from the vector and add back the value of them both, and while i have more than one number, continue doing it. So by theory whatever thread gets there first takes two numbers,that wont be in the vector again, while other threads get other numbers or sum them.

But well the output i get is:

D/Output:: [24]
D/Output:: [48]
D/Output:: [96]
D/Output:: [192]
D/Output:: [384]
D/Output:: [768]
D/Output:: [1536]

Sorry for always asking lengthy questions haha Any help/advice is appreciated.

Thanks, -Kan-

Aucun commentaire:

Enregistrer un commentaire