由于某种原因,在for循环中进行第二次迭代之后,第二次启动thread1时,我得到一个java.lang.IllegalThreadStateException。我认为我根据这里的答案正确使用了加入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();
}
}
}
答案 0 :(得分:8)
您无法多次启动线程。如果要多次执行runnable,请重新创建一个新线程。