0
由于某些原因,在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();
}
}
}
我不知道多谢,我只是将我的主题intialztion移到循环中,它的作用就像一个魅力 – 2013-02-24 01:31:12