首页 > 解决方案 > 限制Java中的并发线程数

问题描述

我正在根据用户输入日期运行多个线程。如果用户输入 15 个日期,它会并行运行 15 个线程,并且对于 10 个日期,它会并行运行 10 个线程

无论用户输入如何,我都需要有一个上限,例如它应该始终运行 5 个线程。我看到 ExecutorService 可以做到这一点,但不知道如何实现

下面是我的示例代码,需要如何在此实现 ExecutorService -

   List<FactorialThread> threads = new ArrayList<>();

         int position = 0;
           for (String query:QueryList)

           {
                position++;
                Thread.currentThread().setName("Thread - "+ position);   
             System.out.println(" Inside run thread method executing the query for ..."+query + "for index " + position  );
             threads.add(new FactorialThread(FileName,query,Thread.currentThread().getName()));


           }




            for (Thread thread : threads) {
              //  thread.setDaemon(true);
                thread.setName("Thread"+thread);
                thread.start();
            }

标签: javamultithreading

解决方案


它相对简单:您可以创建一个基于线程池的 ExecutorService。然后,您提交给该服务的任务将由底层池的线程处理。

请参阅此处以获取一个简单的示例。或者 oracle 的“官方”文档,关于如何配置此类线程池的细微差别。


推荐阅读