简体   繁体   English

在java中使用多线程并行化for循环

[英]Parallelize a for loop using multi-threading in java

I have a for loop in java with the following structure that I need to parallelize into a fixed number of threads. 我在java中有一个for循环,具有以下结构,我需要并行化为固定数量的线程。 Lets say that number is in numThreads . 让我们说这个数字在numThreads The for loop is given below. for循环如下。 Note that only the outer loop needs to be parallelized. 请注意,只需要并行化外部循环。 I think I need to use Executor but I can't figure out how to split the workload into different threads, and if that will change my indexes inside the loop in statements like isInsulator[x][y] . 我想我需要使用Executor,但我无法弄清楚如何将工作负载分成不同的线程,如果这将改变我在isInsulator[x][y]类的语句中的循环内的索引。 basically I want different threads splitting the value of X and running a for loop for those x values assigned to them. 基本上我想要不同的线程分割X的值并为分配给它们的那些x值运行for循环。 Does that make sense? 那有意义吗? Can anyone help me achieve this or maybe push me in the right direction please? 任何人都可以帮助我实现这个目标,或者可能会让我朝着正确的方向前进

  1. Write a benchmark (so you can prove it's really faster with parallel processing), use JMH. 写一个基准测试(所以你可以用并行处理证明它真的更快),使用JMH。
  2. Rewrite the code to be a produce_inputs->process->collect_or_summarize pipeline 将代码重写为produce_inputs->process->collect_or_summarize管道
  3. Use parallel Stream s API (it uses an internal fork-join pool tuned to the number of CPUs on the box). 使用并行Stream的API(它使用一个内部fork-join池调整到盒子上的CPU数量)。
  4. Compare the performance of sequential vs paralle processing. 比较顺序和并行处理的性能。
int result = IntStream.generate(() -> 42) // lazy inputs source
        .limit(100) // limit number of inputs
        .parallel() // use parallel processing
//      .sequential() // ...or sequential processing
        .map(x -> x + 1) // do the processing
        .reduce(0, Math::addExact); // summarize the result
//      .collect(toList()); // ...or just collect it to a container

You can declare a fixed thread pool (it will initialize and use only the specified number of threads): 您可以声明一个固定的线程池(它将初始化并仅使用指定数量的线程):

Executor executor = Executors.newFixedThreadPool(numThreads);

You have to submit X tasks to the thread pool: 您必须将X任务提交到线程池:

for (int i = 0; i < X; i++) {
        final int x = i;
        executor.execute(() -> submitTask(x));
}

In the method submitTask you can define your logic: 在方法submitTask中,您可以定义您的逻辑:

private void submitTask(final int x) {
    for (int y = 0; y < Y; y++) {
        //do stuff
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM