ArrayList 线程不安全的未解之谜

我用两个线程同时向ArrayList中增加String类型的数据,每个线程加一个数据,结果出现了
null,B1 集合长度为2的情况,请问这个null是怎么产生的?源码如下,多运行几次就会出现
这个结果。
 
 
import java.util.ArrayList;
import java.util.List;
public class ExtendsThread {
    public List<String> numberList = new ArrayList<String>();
    class AddThread extends Thread {
        public AddThread(String name) {
            super(name);
        }
        @Override
        public void run() {
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                numberList.add(getName() +"1");
        }
    }
    public static void main(String[] args) {
        ExtendsThread main = new ExtendsThread();
        AddThread a = main.new AddThread("A");
        AddThread b = main.new AddThread("B");
        a.start();
        b.start();
        try {
            Thread.sleep(3000); // 让子线程先运行,之后再输出集合中的内容
        } catch (Exception e) {
            // TODO: handle exception
        }
        System.out.println("集合内的数据为:");
        for (String val : main.numberList) {
            System.out.print(val + ",");
        }
        System.out.println();
        System.out.println("集合长度为" + main.numberList.size());
    }
}

还有一种情况,我已经可以理解了,就是输出:A1,集合长度为1,因为两个线程同时拿到ArrayList中的size值,初值为0,这样两个线程都在0位置赋值,之后各自的size+1,两个线程的size都是1,这样就得到了,A1,集合长度为1的结果。

    欢迎大家留言帮忙解释这个输出结果!!

猜你喜欢

转载自blog.csdn.net/zhangjin1120/article/details/80075816