Please check this code out , it says that program ran too long and was closed!
Help me please;
package com.codegym.task.task16.task1607;
import java.util.ArrayList;
import java.util.List;
/*
Horse racing
*/
public class Solution {
//Main method , figure out later;
public static void main(String[] args) throws InterruptedException {
List<Horse> horses = prepareHorsesAndStart(10);
while (calculateHorsesFinished(horses) != horses.size()) {
}
}
// Method which need to be implemented
public static int calculateHorsesFinished(List<Horse> horses) throws InterruptedException {
int finishedCount = 0;
for (int i = 0 ; i < horses.size()-1 ; i++){
if (horses.get(i).isFinished){
finishedCount++;
}
if (!horses.get(i).isFinished){
System.out.println("Waiting for " + horses.get(i).getName());
horses.get(i).join();
}
}
return finishedCount;
}
// One more method , doesn't look at it
public static List<Horse> prepareHorsesAndStart(int horseCount) { // Method which return List of horses;
List<Horse> horses = new ArrayList<>(horseCount); // Create ArrayList with Horse type;
String number; // Create variable number
// Open a loop
for (int i = 1; i < horseCount + 1; i++) {
number = i < 10 ? ("0" + i) : "" + i; // Attention; // In here number will get - number = "01" or number = "11"
horses.add(new Horse("Horse_" + number)); // Almost guess // All done
}
// Open a loop
for (int i = 0; i < horseCount; i++) { // In here each horses in list start to run method from thread;
horses.get(i).start(); // Attention;
}
return horses;
}
// First figure out what class does
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; // Here s = 0 ; s = "1";
if (i == 1000) {
s = " has finished the race!"; // s = "has finished the race!"
System.out.println(getName() + s); // Horse_1000 has finished the race
isFinished = true;
}
}
}
}
}