0
I am trying to make a multithread sum but the value is very discrepant: the value that should be the sum of all numbers 499500
what is being 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);
}
}
Soma 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];
}
}
}
for(int i = inicio; i < i + qtd;i++){
Is that right? What should he do?– Math
start the sum at a given start position (because several threads are summing up in dierents) and stop at the last position before the start position of the next thread add up
– Ricardo
I still don’t understand your code, but you’re bound to get out of this
for
the variableqtd
should be of0
down, right? And I don’t see the variableqtd
being modified nowhere after startup.– Math
Qtd is not to be modified at any location, and is leaving the.
– Ricardo
@Math this
qtd
is the amount of values of the vector to be read and summed.– Ricardo