试图弄清楚 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)
感谢您的帮助,如果有好的教程,我将非常感谢您提供链接。
附言。如果 java 中有任何调试器,如 python 中的 pdb,请告诉我。 谢谢!
最佳答案
您应该看看更高级别的线程实用程序,例如 ExecutorService 和 ThreadPools。
您永远不应该手动终止线程,我建议一般情况下避免手动创建/管理线程。
如果要等待多个线程完成,您可能需要使用 CountDownLatch。 这是 an example .
关于java - 限制在java中同时执行的最大线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19386544/