试图弄清楚Java中的线程是如何工作的,我只想通过将它们全部放入数组来限制可运行线程的执行,然后在循环中检查它们中的一些是否完成并将它们弹出,以便有可能产生一个新线程,出现异常在这段代码中:
public class testThread implements Runnable {
public void run () {
try {
Thread.sleep(1000);
} catch(InterruptedException e){}
System.out.println("This is the test thread");
}
public static void main (String args[]) {
int max_threads = 5;
Thread worker;
ArrayList<Thread> all_workers = new ArrayList<Thread>(max_threads );
for (int i =0; i<50; i++) {
if (all_workers.size()<max_threads){
worker = new Thread (new testThread());
all_workers.add(worker);
worker.start();
} else{
System.out.println("i ran all");
while(all_workers.size()>=max_threads){
try{
System.out.println("Waiting for some to finish");
int counter = 0;
for (Thread wrk: all_workers){
if (!wrk.isAlive()){
all_workers.remove(counter);
}
counter ++ ;
}
Thread.sleep(500);
} catch (InterruptedException e){
System.out.println("Catched unhandled ");
}
}
}
}
for(Thread wrk: all_workers){
try {
wrk.join();
} catch (InterruptedException e) {
}
}
}
}
我运行它时遇到的异常:
anybody@anymachine ~/java $ java testThread
i ran all
Waiting for some to finish
Waiting for some to finish
This is the test thread
This is the test thread
This is the test thread
This is the test thread
This is the test thread
Waiting for some to finish
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819)
at java.util.ArrayList$Itr.next(ArrayList.java:791)
at testThread.main(testThread.java:39)
感谢您的帮助,如果有一个好的教程,我会非常感谢链接。
PS。如果在 java 中有任何调试器,例如 python 中的 pdb,请告诉我。谢谢你!