java - 限制在java中同时执行的最大线程数

标签 java multithreading

试图弄清楚 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/

相关文章:

java - Hibernate 4 不同和一起排序

填充 map 对象时出现 Java NullPointerException

java - 内存不足错误时堆转储的 JRockit 设置

python - 使用线程时单元测试 Python 中的 time.sleep()

java - 使用 Gradle 执行 Cucumber 测试场景

java - 调用 AWS API - 签名,身份验证 header - 在 android 中使用 OkHTTP

java - 我正在尝试在 Android Studio 中实现蓝牙功能,需要一些帮助来解决连接问题

c# - 当 ThreadPool 中的事件线程数大于 ThreadPool.GetMinThreads() 时启动任务

java - 在 call() 方法的返回语句执行之前具有对象引用的 future 对象

c - 对 `fprintf(stdout, ...)` 和 `fprintf(stderr, ...)` 的调用是否保证不会与多个线程交错?