class RaceDemo {
public static void main(String[] args) {
Racer racer = new Racer();
Thread tortoiseThread = new Thread(racer, "Tortoise");
Thread hareThread = new Thread(racer, "Hare");
//Race to start. tell threads to start
tortoiseThread.start();
hareThread.start();
try {
hareThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Racer implements Runnable {
public static String winner;
public void race() {
for (int distance = 1; distance <= 100; distance++) {
System.out.println("Distance Covered by " + Thread.currentThread().getName() + "is:" + distance + "meters");
//Check if race is complete if some one has already won
boolean isRaceWon = this.isRaceWon(distance);
if (isRaceWon) {
break;//Si alguno ya ganó, el otro no sigue
}
}
}
// - -
// - -
// - -
// - -
// Thread1 Thread2
// race 1 race 2
//
private boolean isRaceWon(int totalDistanceCovered) {
boolean isRaceWon = false;
if ((Racer.winner == null) && (totalDistanceCovered == 100)) {
String winnerName = Thread.currentThread().getName();//Devuelve el nombre del thread que está ejecutando el código en ese momento.
Racer.winner = winnerName; //setting the winner name
System.out.println("Winner is :" + Racer.winner);
isRaceWon = true;
} else if (Racer.winner == null) {
isRaceWon = false;
} else if (Racer.winner != null) {
isRaceWon = true;
}
return isRaceWon;
}
@Override
public void run() {
this.race();
}
}
Is the method of race()
the same as that used for each thread?
In other words, the thread1 calls the method and the thread2 also therefore, in console it would not have to leave that both won?
One before the other, but as they called the method twice, I would have to win one and then the other ...
But in console only jumps that won one and then cut the program ...