3
The implementation below is merely a test class to test competition in Java. Multiple Threads are created that execute a method that adds up, then a return is displayed showing the sum result. According to the values already implemented in the code below, the correct result is 100, but it oscillates between 90 and 100 since for some implementation error, the parallel process prevents to always return the correct value, displaying the result without waiting for all Threads to finish executing the sum.
What I did wrong?
BEGINNING OF 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);
}
}