The Unsolved Mystery of ArrayList's Thread Unsafety

I use two threads to add String type data to the ArrayList at the same time, each thread adds one data, the result
is null, the length of the B1 collection is 2, how does this null come about? The source code is as follows, and
this .
 
 
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); // Let the child thread run first, and then output the contents of the collection
        } catch (Exception e) {
            // TODO: handle exception
        }
        System.out.println("The data in the collection is: ");
        for (String val : main.numberList) {
            System.out.print(val + ",");
        }
        System.out.println();
        System.out.println("The length of the collection is" + main.numberList.size());
    }
}

There is another situation that I can already understand, that is, the output: A1, the length of the collection is 1, because the two threads get the size value in the ArrayList at the same time, and the initial value is 0, so that both threads are assigned at the 0 position, and then The respective size+1, the size of both threads is 1, so we get, A1, the result that the set length is 1.

    Welcome to leave a message to help explain this output! !

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324826880&siteId=291194637