首页 > 解决方案 > 处理多线程时如何避免瓶颈?

问题描述

我有以下循环:

// 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();
}

问题是,在这种情况下使用多线程来避免排队的推荐方法是什么?

标签: javamultithreading

解决方案


一种简单的方法是使用-ExecutorService根据您的描述,您希望每个处理器使用一个线程:

int nThreads = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(nThreads);

for (MyObject test: myList) {
  executor.submit(test::calculate);
}

executor.shutdown();

执行器维护一个内部队列,该队列将保存任务直到前一个任务完成。


推荐阅读