首页 > 解决方案 > 两个线程之间的同步 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

标签: javamultithreading

解决方案


输出应该是:2000000

不,有三个原因:

  1. 您正在打印两件事,因此输出不会是单个数字。
  2. 当每个线程碰巧添加了 1000000 个东西时,它会打印大小;你对此时其他线程做了多少一无所知。
  3. 您没有以同步的方式访问大小,因此您可能会获得非最新的值。

推荐阅读