错误示例:
public List<String> test() throws NuMaxCloudCommonException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<String> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Future<?> future = executorService.submit(() -> {
list.add("a");
});
}
return list;
}
返回结果:[a],[a,a],[a,a,a]不一定,就是因为线程池使用了非线程安全的列表,所以会出现元素空的情况
正确示例:
public List<String> test() throws NuMaxCloudCommonException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<String> list = Collections.synchronizedList(new ArrayList<>());
for (int i = 0; i < 3; i++) {
Future<?> future = executorService.submit(() -> {
list.add("a");
});
}
return list;
}
结果一直是:
[
"a",
"a",
"a"
]
标签:executorService,Java,示例,List,list,多线程
From: https://www.cnblogs.com/beijie/p/18339219