Насколько я понял метод join заставляет ждать остальные потоки пока не завершится поток у которого был вызван метод join.
Так вот вопрос у меня такой вывод:
All horses start the race!
Waiting for Horse_01
Horse_02 has finished the race!
Horse_03 has finished the race!
Horse_10 has finished the race!
Horse_07 has finished the race!
Horse_06 has finished the race!
Horse_05 has finished the race!
Horse_01 has finished the race!
Horse_09 has finished the race!
Horse_08 has finished the race!
Waiting for Horse_04
Horse_04 has finished the race!
судя по этому выводу у потока Horse_01 вызвался метод join который должен остановить остальные потоки, тогда исходя из моей логики после строки
Waiting for Horse_01
должна вывестись строка
Horse_01 has finished the race!
но она выводится почти в конце почему так?
код программы
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 (Horse hors : horses) {
if ((!hors.isFinished())) {
System.out.println("Waiting for " + hors.getName());
hors.join();
}else finishedCount++;
}
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 < 1001; i++) { // Delay
s += "" + i;
if (i == 1000) {
s = " has finished the race!";
System.out.println(getName() + s);
isFinished = true;
}
}
}
}
thread1иthread2. Тогда, если первый поток выполнитон будет дожидаться окончания работы потокаthread2, и лишь после этого продолжит своё выполнение.join().