[英]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:需要考虑的事项:
What I have tried:我试过的:
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
的并且无法分配。
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.