ArrayList<Integer> 如何在下面的程序中存储 'null' 值?
How an ArrayList<Integer> stores 'null' value in the below program?
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());
}
}
我只是递增计数并将该值添加到数组列表中。有时它存储预期值,但有时不存储(ArrayList<Integer>
包含 'null' 值)。请帮助我解决这个问题。
From the Javadoc of ArrayList
:
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
您正在从多个线程添加元素,但没有在外部同步它。因此,您很可能会在列表中看到未定义的行为 - 例如,当您从未实际添加 null.
时,null
元素
您可以使用 Javadoc 中的提示轻松解决此问题:
List<Integer> numbers = Collections.synchronizedList(new ArrayList<>());
(请注意,您可能仍然会看到其他 "unexpected" 行为,例如,相同的数字被添加两次,因为 count
没有以原子方式递增;或者元素在列表)
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());
}
}
我只是递增计数并将该值添加到数组列表中。有时它存储预期值,但有时不存储(ArrayList<Integer>
包含 'null' 值)。请帮助我解决这个问题。
From the Javadoc of ArrayList
:
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.
您正在从多个线程添加元素,但没有在外部同步它。因此,您很可能会在列表中看到未定义的行为 - 例如,当您从未实际添加 null.
时,null
元素
您可以使用 Javadoc 中的提示轻松解决此问题:
List<Integer> numbers = Collections.synchronizedList(new ArrayList<>());
(请注意,您可能仍然会看到其他 "unexpected" 行为,例如,相同的数字被添加两次,因为 count
没有以原子方式递增;或者元素在列表)