多线程下java.util.ConcurrentModificationException问题解决

private List<String> mData = new ArrayList<>();
private List<String> mCloneData;
private int count = 0;

public void test() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                for (String string : getData()) {
                    Log.i(TAG, string);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                mData.add(count++ + "");
                mCloneData = null;
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}

private List<String> getData() {
    if (mCloneData == null) {
        mCloneData = (List<String>) ((ArrayList) mData).clone();
    }
    return mCloneData;
}

参考链接:

java.util.ConcurrentModificationException 异常问题详解

发表评论