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