Somewhat Multithead

0

I'm trying to make a multithreaded summation but the value is very dissimilar: the value that should be the sum of all numbers 499500 what is the result: 1561250

Main Class:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Ex1 {

    public static void main(String[] args) throws InterruptedException{
        int soma = 0;
        int qtd = 250;
        int inicio = 0;
        int qtdThreads = 4;
        int qtdValores = 1000;
        int[] a = new int[qtdValores];
        for (int i = 0; i < qtdValores; i++){
            a[i] = i;
        }

         //cria pool de threads para execução de tarefas
        ThreadPoolExecutor p = new ThreadPoolExecutor(5, 10, 1, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(10));
        List<Soma> listThread = new ArrayList<Soma>();

        for(int i = 0; i < qtdThreads; i++){
            listThread.add(new Soma(a,inicio));
            p.submit(listThread.get(i));
            inicio += qtd;
        }

        //força a execução e finalização das threads
        p.shutdown();

        //aguarda finalização das threads em execução
        p.awaitTermination(1, TimeUnit.DAYS);

        for(int i = 0; i < qtdThreads; i++){
            soma += listThread.get(i).soma;
        }

        System.out.println(soma);
    }

}

Sum class:

public class Soma extends Thread{
    private int qtd = 250;
    public int inicio;
    public int soma = 0;
    public int[] a;

    public Soma(int[] a, int inicio){
        this.a = a;
        this.inicio = inicio;
    }

    public void run(){
        for(int i = inicio; i < i + qtd;i++){
            soma += a[i];
        }
    }
}
    
asked by anonymous 07.05.2015 / 15:11

1 answer

2

The problem is in the following code snippet:

public void run(){
    for(int i = inicio; i < i + qtd;i++){
        soma += a[i];
    }
}

You should do:

public void run(){
    for(int i = inicio; i < inicio + qtd;i++){
        soma += a[i];
    }
}

You have assumed that it should go from start to finish plus quantity, but using i rather than inicio its value that should be the initial varies by each iteration.

    
07.05.2015 / 15:42