java - 处理多线程时如何避免瓶颈?
问题描述
我有以下循环:
// myList is an ArrayList (10000 elements)
for(MyObject test : myList) {
test.calculate();
}
而且我认为它是并行化的一个很好的候选者,因为每个calculate()
操作都不依赖于其他任何东西,它只使用同一个对象中的一些变量进行一些数学运算。
我知道执行以下操作会对性能产生负面影响,因为我将创建 10000 个线程,这将在我的 4 核处理器上创建一个巨大的队列:
// myList is an ArrayList (10000 elements)
for(MyObject test : myList) {
Thread thread = new Thread() {
public void run() {
test.calculate();
}
};
thread.start();
}
问题是,在这种情况下使用多线程来避免排队的推荐方法是什么?
解决方案
一种简单的方法是使用-ExecutorService
根据您的描述,您希望每个处理器使用一个线程:
int nThreads = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(nThreads);
for (MyObject test: myList) {
executor.submit(test::calculate);
}
executor.shutdown();
执行器维护一个内部队列,该队列将保存任务直到前一个任务完成。
推荐阅读
- python - 正确访问嵌套 Python 字典的问题
- python - 导出到excel时如何设置列标题?
- swift - UITableView 中的最后一个单元格始终与表格中最高的单元格具有相同的高度?
- python - 我在 Windows 10 中使用 python 2.7,并且在 juptyr 笔记本中出现名称错误,我该如何解决这个问题?
- javascript - jQuery部分数组匹配用户输入?
- flutter - 如何找到映射到特定 pod 版本的包版本?
- javascript - 使用 AJAX 将对象从谷歌脚本分配给局部变量
- scala - /hbase/meta-region-server 的连接丢失
- java - java中无法解决的错误,有什么解决办法吗?
- python - Python random.choices() 没有给出想要的输出