My problem is as follows, I have a runner class, the only thing he does is a method run
(thread) that simulates the distance traveled and is saved in the variable distance that is a summation of the result of the Math.Random();
My problem is this:
How, from class matches, do you detect that you win?
I have tried several things like creating a method in a corridor that says distance traveled, but of course in the race class I do not know how to orient it, I have not found an example like that. I have created this simple example of concurrency because I know that this way I will find out about the guidelines that must be followed.
This is my code:
import java.util.logging.Level;
import java.util.logging.Logger;
class pista_carrera {
private corredor c1;
private corredor c2;
private int meta;
public pista_carrera(corredor corredor1, corredor corredor2, int meta) {
this.c1 = corredor1;
this.c2 = corredor2;
this.meta = meta;
}
public synchronized void empezarCarrera() {
c1.run();
c2.run();
while (c1.getDistanciaRecorrida() < meta || c2.getDistanciaRecorrida() < meta) {
}
}
}
class corredor extends Thread {
private int distancia;
private String nombre;
public corredor(String nombre) {
distancia = 0;
this.nombre = nombre;
}
@Override
public void run() {
while (true) {
int random = (int) Math.floor(Math.random() * (1 - (10 + 1)) + (10));
distancia += random;
System.out.println("[" + nombre + "]Ditancia = " + distancia + " m");
try {
sleep(800);
} catch (InterruptedException ex) {
Logger.getLogger(corredor.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public int getDistanciaRecorrida() {
return this.distancia;
}
}
public class Carrera {
public static void main(String[] args) {
pista_carrera pista;
corredor corredor1 = new corredor("Ernesto");
corredor corredor2 = new corredor("Jesus");
corredor1.start();
corredor2.start();
}
}