cannot pass 3rd requirement....
Also, the output is not coherent/consistent: it displays some of the horse more than once, but I think it's because the while loop driving it, doesn't constitute the best way to start the whole thread ?
package com.codegym.task.task16.task1607;
import java.util.ArrayList;
import java.util.List;
/*
Horse racing
*/
public class Solution {
public static void main(String[] args) throws InterruptedException {
//this statement declares a LIST with HORSE objects, and calls a function to populate it with 10 horses
//It doesn't put populate the list, it sets the list equal to the return of the function, that populates the list
List<Horse> horses = prepareHorsesAndStart(10);
//this while loop continues a process until all horses finished
while (calculateHorsesFinished(horses) != horses.size()) {
}
}
public static int calculateHorsesFinished(List<Horse> horses) throws InterruptedException {
int finishedCount = 0;
for (int i = 0;i< horses.size();i++){
if (horses.get(i).isFinished()){
finishedCount++;
System.out.println(horses.get(i).getName() + " has finished the race!");
}
else {
System.out.println("Waiting for " + horses.get(i).getName());
horses.get(i).join();
}
}
return finishedCount;
}
public static List<Horse> prepareHorsesAndStart(int horseCount) {
//declare a LIST with type = HORSE object, and make the size = input number (10)
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;
}
}
}
}
}