По какой-то причине после второй итерации в цикле for я получаю java.lang.IllegalThreadStateException сразу, когда thread1 запускается во второй раз. Я думал, что правильно использую соединение в соответствии с ответом здесь How to wait for a number of threads to complete?. Мой вопрос в том, почему на второй итерации я получаю исключение.Попытка дождаться завершения всех потоков
public void runThreads(){
int numofTests;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of iterations to be completed:");
numofTests = Integer.parseInt(in.nextLine());///Gets the number of tests from the user
Agent agent = new Agent(numofTests);
Smoker Pat = new Smoker ("paper", "Pam");
Smoker Tom = new Smoker ("tobacco", "Tom");
Smoker Matt = new Smoker ("matches", "Matt");
Thread thread1 = new Thread(Pat);
Thread thread2 = new Thread(Tom);
Thread thread3 = new Thread(Matt);
Thread thread4 = new Thread(agent);
for (int i = 0; i < numofTests; i++){
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
thread1.join();
thread2.join();
thread3.join();
thread4.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Я понятия не имел, спасибо, что я просто перевел мой поток в цикл, и он работает как шарм –