简体   繁体   English

Java中的并行数组拷贝

[英]Parallel array copy in Java

I'm looking to copy an array into another in parallel , for example:我希望将一个数组并行复制到另一个数组中,例如:

int[] a = {1, 3, 5, 7, 9};
int[] b = new int[a.length];
for(int i = 0; i < a.length; i++) // parallel
{
   b[i] = a[i];
}

In this example I would like one thread to copy the first 3 indexes, and another to copy the other 2. Of course it can be in any other variation as well.在此示例中,我希望一个线程复制前 3 个索引,另一个复制其他 2 个。当然,它也可以是任何其他变体。


Things to consider:需要考虑的事项:

  1. I am planning to run this on very large arrays so a small overhead is ok我打算在非常大的 arrays 上运行它,所以小的开销是可以的
  2. There might be more code added to the loop body, for example another array - c which will get a[i]+1循环体中可能添加了更多代码,例如另一个数组 - c 将获得 a[i]+1

What I have tried:我试过的:

  1. IntStream.range : IntStream.range
    IntStream.range(0, a.length).parallel().forEach(i -> {
        b[i] = a[i];
    });

This resulted in Local variable percentiles defined in an enclosing scope must be final or effectively final error since b is not final and cannot be assigned.这导致在Local variable percentiles defined in an enclosing scope must be final or effectively final错误,因为b不是final的并且无法分配。

  1. fork/join: might be it, but looking for other solution which does not involve declaring a new class or extending the existing one. fork/join:可能是这样,但正在寻找不涉及声明新 class 或扩展现有解决方案的其他解决方案。

There's no reason to do this in parallel;没有理由并行执行此操作。 because you're working with an int[] , you can use clone() to copy it:因为您正在使用int[] ,所以可以使用clone()来复制它:

int[] a = {1, 3, 5, 7, 9};
int[] b = a.clone();

If, for some reason, you still want to do this in parallel, then you can use Arrays#parallelSetAll :如果出于某种原因,您仍想并行执行此操作,则可以使用Arrays#parallelSetAll

Arrays.parallelSetAll(b, i -> a[i]);

For each snippet, the elements of b are equivalent:对于每个片段, b的元素是等价的:

[1, 3, 5, 7, 9]

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

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