gpt4 book ai didi

java - Java中并发线程数的限制

转载 作者:行者123 更新时间:2023-12-02 01:35:56 25 4
gpt4 key购买 nike

我正在根据用户输入日期运行多个线程。如果用户输入 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();
}

最佳答案

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

参见here举一个简单的例子。还是“官方”documentation来自oracle关于如何配置此类线程池的细微差别。

关于java - Java中并发线程数的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55273584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com