The implementation below is merely a test class to test competition in Java. Several Threads are created that execute a method that makes a sum, then a return is displayed showing the result of the sum. According to the values already implemented in the code below, the correct result is 100, but it is oscillating between 90 to 100 since for some implementation error, the parallel process prevents always returning the correct value, displaying the result without waiting all Threads finish executing the sum.
What did I do wrong?
STARTING THE CLASS
import java.util.ArrayList;
import java.util.List;
public class ExercicioFinal {
private final static List<Soma> listaSoma = new ArrayList<Soma>(0);
private static final int LIMITE = 10;
public static void main(final String[] args) throws InterruptedException {
for (int i = 0; i < LIMITE; i++) {
listaSoma.add(new Soma(10));
}
for (final Soma soma : listaSoma) {
new Thread(soma).start();
}
exibirResultado(0);
}
private static void exibirResultado(final int i) throws InterruptedException {
final Soma s = listaSoma.get(i);
synchronized (s) {
if (!s.foiExecutado()) {
s.wait();
}
if ((i + 1) < listaSoma.size()) {
exibirResultado(i + 1);
} else {
if (s.foiExecutado()) {
Soma.exibe();
} else {
exibirResultado(i);
}
}
}
}
}
class Soma implements Runnable {
private static int resultado;
private final int valor;
private boolean executou = false;
public Soma(final int valor) {
this.valor = valor;
}
@Override
public void run() {
synchronized (this) {
try {
Thread.sleep(1);
} catch (final InterruptedException e) {
e.printStackTrace();
}
resultado += valor;
executou = true;
this.notify();
}
}
public boolean foiExecutado() {
return executou;
}
public static void exibe() {
System.out.println(resultado);
}
}