I have a string exercise, it's a relay race. I find out the time of each athlete with a random. I have an athlete class that extends from thread and a helper class that helps me with a number of things. The problem is that at the end of the run it should print once all the threads have passed the end of the run total time. but for some reason it doesn't and I don't quite understand why.
public class Atleta extends Thread {
private String relevo;
public Atleta(String relevo) {
super(relevo);
}
public void run() {
double tiempo = 0;
synchronized (getClass()) {
if (VAux.getTiempo() == 0) {
System.out.println("Comienza a correr " + getName());
tiempo = (double) (Math.random() * (11 - 9) + 9);
VAux.setTiempo(+tiempo);
VAux.setAcumuladorDHilos(+1);
getClass().notifyAll();
} else {
System.out.println("pasa el relevo y comienza a correr " + getName());
tiempo = (double) (Math.random() * (11 - 9) + 9);
VAux.setTiempo(+tiempo);
VAux.setAcumuladorDHilos(+1);
getClass().notifyAll();
}
try {
System.out.println("el dorsal: " + getName() + " ha tardado: " + tiempo);
getClass().wait();
} catch (java.lang.InterruptedException e) {
}
getClass().notifyAll();
if (VAux.hilosAUsar == VAux.getAcumuladorDHilos()) {
System.out.println("final de la carrera, timepo total: " + VAux.getTiempo());
}
}
}
}
and this is the assistant
public class VAux {
private static double tiempo = 0;
private static int acumuladorDHilos = 0;
public static final int hilosAUsar =4;
public VAux() {
}
public static double getTiempo() {
return tiempo;
}
public static void setTiempo(double tiempo) {
VAux.tiempo = tiempo;
}
public static int getAcumuladorDHilos() {
return acumuladorDHilos;
}
public static void setAcumuladorDHilos(int acumuladorDHilos) {
VAux.acumuladorDHilos = acumuladorDHilos;
}
}
the main
public static void main(String[] args) {
Atleta a1 = new Atleta("1");
Atleta a2 = new Atleta("2");
Atleta a3 = new Atleta("3");
Atleta a4 = new Atleta("4");
a1.start();
a2.start();
a3.start();
a4.start();
}
Hello, I leave you some changes so that you initially achieve what you ask for, which is to print the final section of the race, total time.
Maybe the ExecutorService will help you. You have more info here and here
In short: