java - 两个线程之间的同步 Arraylist 不返回相同的值
问题描述
我有以下代码:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class MyThread implements Runnable{
private List<Integer> myList;
public MyThread(List<Integer> list){
this.myList = list;
}
private void updateList(int i){
synchronized (myList) {
myList.add(i);
}
}
@Override
public void run() {
for( int i = 0; i < 1000000;i++){
updateList(i);
}
System.out.println("end: " + myList.size());
}
}
public class MyExecutor {
private List<Integer> taskList = new ArrayList<>();
private void launch(){
ExecutorService executorService= Executors.newFixedThreadPool(10000);
executorService.execute(new MyThread(taskList));
executorService.execute(new MyThread(taskList));
executorService.shutdown();
}
public static void main(String[] args) {
MyExecutor test = new MyExecutor();
test.launch();
}
}
输出应该是:2000000
我会得到不同的结果,这意味着这两个线程正在替换彼此的值。
我不知道问题出在哪里,对此代码进行了多次修改,但都没有解决问题。(替换为 Vector / 在构造函数中添加了同步 / 添加了 volatile)
为什么这段代码不能正常工作?
编辑
在这两个线程我希望得到 1000000
解决方案
输出应该是:2000000
不,有三个原因:
- 您正在打印两件事,因此输出不会是单个数字。
- 当每个线程碰巧添加了 1000000 个东西时,它会打印大小;你对此时其他线程做了多少一无所知。
- 您没有以同步的方式访问大小,因此您可能会获得非最新的值。
推荐阅读
- sharepoint-online - 使用/安装 @pnp/sp 模块时遇到问题
- flutter-layout - Flutter:如何将“标题图像”和“ListView”放在同一个滚动条中?
- python - 在 Alexa Skill 中编辑声音 - Python
- ajax - .NET Core 从 Razor 页面向控制器进行 AJAX 调用
- java - 如何在 XML 的特定位置插入新节点?
- azure-ad-b2c - Localised message for RestAPI error response in B2C custom policy
- vue.js - Vue - 有条件地传递道具
- python - 通过 str.contains() 进行索引,然后将值插入另一列
- python - 将金额除以行
- laravel - Laravel 更新关系