package com.javarush.task.task16.task1607;
import java.util.ArrayList;
import java.util.List;
/*
Horse Racing
*/
public class Solution {
public static void main(String[] args) throws InterruptedException {
List<Horse> horses = prepareHorsesAndStart(10);
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())
{
// System.out.println(horses.get(i).getName()+ " has finished the race!");
finishedCount++;
}
else
{
System.out.println("Waiting for " + horses.get(i).getName());
horses.get(i).join();
}
}
return finishedCount;
}
public static List<Horse> prepareHorsesAndStart(int horseCount) { // возвращает количество финишировавших лошадей
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));
}
System.out.println("All horses start the race!");
for (int i = 0; i < horseCount; i++) {
horses.get(i).start();
}
return horses;
}
}
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 < 100001; i++) { // Delay
s += "" + i;
if (i == 10000) {
s = " has finished the race!";
System.out.println(getName() + s);
isFinished = true;
}
}
}
}
1) Как я понимаю, поправьте меня, пожалуйста, если я не прав участок кода horses.get(i).start(); запускает потоки, исходя из кода моей задачи их будет 10, т.к. лошадок 10.
2) Скажите, пожалуйста, что делает метод public void run()?
3) Почему при разных значениях i и в методе public void run()
выводятся разные значения в консоль, например:
при первом i=4000, втором i=2899 следующее:
All horses start the race!
Waiting for Horse_01
Horse_07 has finished the race!
Horse_10 has finished the race!
Horse_08 has finished the race!
Horse_03 has finished the race!
Horse_02 has finished the race!
Horse_06 has finished the race!
Horse_04 has finished the race!
Horse_09 has finished the race!
Horse_01 has finished the race!
Waiting for Horse_05
Horse_05 has finished the race!
при i=1000 и i=199 вот такие значения
All horses start the race!
Waiting for Horse_01
Horse_02 has finished the race!
Horse_04 has finished the race!
Horse_06 has finished the race!
Horse_08 has finished the race!
Horse_10 has finished the race!
Horse_09 has finished the race!
Horse_07 has finished the race!
Horse_05 has finished the race!
Horse_03 has finished the race!
Horse_01 has finished the race!
Почему в первом случае второй строчкой идёт, что седьмая лошадь закончила забег, а во втором случае второй строчкой идёт, что вторая лошадь закончила забег.
СПАСИБО!!!
Александр
16 уровень
Добрый вечер! Прошу пояснить логику работы программы. Спасибо большое
Обсуждается
Комментарии (2)
- популярные
- новые
- старые
Для того, чтобы оставить комментарий Вы должны авторизоваться
Aleksandr Marchenko
14 августа 2021, 22:38полезный
Уже ранее было сказано, что как раз данный метод run, и создает "случайность" среди лошадей, так как потоки не синхронизированы и выполняются в перемешку, то непонятно какой поток раньше досчитает до 1000(что происходит в методе run).
+2
Александр
16 августа 2021, 20:32
Спасибо!
0