ArrayList <integer>如何在以下程序中存储“ null”值?

时间:2018-10-08 12:42:45

标签: java multithreading arraylist concurrency executorservice

clear

我只是增加计数并将该值添加到数组列表中。有时它存储期望值,但有时不存储(public class SampleExecutorService { private int count = 0; List<Integer> numbers = new ArrayList<>(); private void increment() { count++; numbers.add(count); } public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(10); SampleExecutorService obj = new SampleExecutorService(); Runnable task = obj::increment; for (int i = 0; i < 20; i++) { executorService.submit(task); } executorService.shutdown(); try { executorService.awaitTermination(2, TimeUnit.MINUTES); } catch (InterruptedException e) { e.printStackTrace(); } obj.numbers.stream().forEach(System.out::println); System.out.println("count : " + obj.numbers.size()); } } 包含“空”值)。请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:2)

From the Javadoc of ArrayList

  

请注意,此实现未同步。如果有多个线程同时访问ArrayList实例,并且至少有一个线程在结构上修改了列表,则必须在外部进行同步。

您要从多个线程中添加元素,但不能在外部进行同步。因此,您很可能会在列表中看到未定义的行为-例如,当您从未实际添加null时,会使用null个元素。

您可以使用Javadoc中的提示来简单地解决此问题:

List<Integer> numbers = Collections.synchronizedList(new ArrayList<>());

(请注意,您可能还会看到其他“意外”行为,例如两次添加相同的数字,因为count不会自动增加;或者元素在列表中的排列顺序不正确)