java - 限制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();
}
解决方案
推荐阅读
- javascript - 承诺所有猫鼬找到返回不完整的值
- java - 如何在Java中拆分括号和
- css - :nth-child(1) 不工作 - 使用 html 示例
- react-native - React Native - 模式中未指定“useNativeDriver”
- c++ - C ++ RasPi - 无限循环中的分段错误
- android - 如何将 React Native 应用程序中的通知图标用于某些 RNBridge?
- python - 读取 json 键值作为不敏感键
- c++ - 初始化动态数组
- aem - 根据 AEM 中的浏览器有条件地包含不同的客户端库?
- python - Chrome 不加载配置文件