1. The calculateHorsesFinished method must return the number of horses that have finished:
Number 2.3 in the conditions says to only count horses as finished if you don't have to wait for them.
In main(): while (calculateHorsesFinished(horses) != horseCount) {} indicates that the calculateHorsesFinished() should run multiple times.
2. The calculateHorsesFinished method must call the isFinished method on each horse in the passed list:
if(!horse.isFinished) called on each horse in horses. Hinted at in #2 to use this syntax.
3. If any of the horses in the passed list has not yet finished, then the calculateHorsesFinished method should display "Waiting for " + horse.getName(). Example output for the first horse: "Waiting for Horse_01":
This is done too.
Please help me understand why each of these is not being validated.
package com.codegym.task.task16.task1607;
import java.util.ArrayList;
import java.util.List;
/*
Horse racing
*/
public class Solution {
public static int horseCount = 10;
public static void main(String[] args) throws InterruptedException {
List<Horse> horses = prepareHorsesAndStart();
while (calculateHorsesFinished(horses) != horseCount) {
}
}
public static int calculateHorsesFinished(List<Horse> horses) throws InterruptedException {
int finishedCount = 0;
for (Horse horse : horses) {
boolean isTrue = horse.isFinished;
if(!isTrue) {
System.out.println("Waiting for " + horse.getName());
horse.join();
} else {
finishedCount++;
}
// System.out.println(finishedCount); //debugging
}
// System.out.println(finishedCount); //debugging
return finishedCount;
}
public static List<Horse> prepareHorsesAndStart() {
List<Horse> horses = new ArrayList<>(horseCount);
String number;
for (int i = 1; i < horseCount + 1; i++) {
number = i < 10 ? ("0" + i) : "" + i;
horses.add(new Horse("Horse_" + number));
}
for (int i = 0; i < horseCount; i++) {
horses.get(i).start();
}
return horses;
}
public static class Horse extends Thread {
private boolean isFinished;
public Horse(String name) {
super(name);
}
public boolean isFinished() {
return isFinished;
}
public void run() {
String s = "";
for (int i = 0; i < 1001; i++) { // Delay
s += "" + i;
if (i == 1000) {
s = " has finished the race!";
System.out.println(getName() + s);
isFinished = true;
}
}
}
}
}