并行化java中的循环

pra*_*een 2 java multithreading openmp

我遇到过openMP,它可以用来并行化c,C++中的for循环.当然,OpenMP可以做的远不止这些.但我很好奇我们是否可以在java中并行化for循环以优化程序的性能.假设我在for循环中有n次迭代,有没有办法并行运行这些迭代?

Tal*_*ala 5

如果每次迭代花费大量时间并且独立于循环中的先前计算,则使用ExecutorService并将计算提交为任务.

ExecutorService executorService = Executors.newFixedThreadPool(4); // number of threads
for (int i = 0; i < n; i++) {
   // declare variables as final which will be used in method run below
   final int count = i;
   executorService.submit(new Runnable() {
       @Override
       public void run() {
           //do your long stuff and can use count variable
       }
   });
}
Run Code Online (Sandbox Code Playgroud)