以下代码在完成并行处理后并未将所有元素放入目标列表中。这有什么原因吗?
public static void main(String[] args) {
List<Integer> source =new ArrayList<>();
List<Integer> destination = new ArrayList<>();
IntStream.range(0, 10000).forEach(element ->{
source.add(element);
});
//System.out.println(source.size());
source.parallelStream().forEach(c->{
destination.add(c);
});
System.out.println("Source Size:"+source.size());
System.out.println("destination size:"+destination.size());
}
输出:
源大小:10000
目的地大小:4343
最佳答案
因为 ArrayList
不是线程安全的集合。使用像 CopyOnWriteArrayList
这样的线程安全集合会使其正确但不一定有效。
改用 Collector
会更简单和正确。例如
source.parallelStream().collect(Collectors.toList())
关于java - 为什么 list.parallelStream().forEach() 不处理 Java 中列表中的所有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60095513/