Bootstrap

ArrayList 多线程报 数组越界异常

使用ArrayList在多线程环境可能会出现ArrayIndexOutOfBoundsException 异常,这篇文章就来看看为什么会出现这个错误。

场景还原

先看看下面的实例:

public class ArrayListConcurrent {

    private static List<Integer> numberList = new ArrayList<>(100000);

    public static class AddToArrayList extends Thread{
        int startNum = 0;

        public AddToArrayList(int startNum){
            this.startNum = startNum;
        }

        @Override
        public void run() {
            int count = 0;
            while (count < 1000000){
                numberList.add(startNum);
                startNum += 2;
                count++;
            }
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new AddToArrayList(0));
        Thread thread2 = new Thread(new AddToArrayList(1));
        thread1.start();
        thread2.start();
    }
}

在运

;