ConcurrentModificationException

下面两个例子, 第一个不会出现Exception, 后面的会有ConcurrentModificationException。

package com.karl.test;

import java.util.List;
import java.util.Vector;

public class TestVectorConcurrent {
    Object obj = new Object();
    public static List<String> v = new Vector<String>();

    private static void init() {
        for (int i = 1; i <= 20; i++) {
            v.add("helloworld:" + i);
        }
    }

    public static void main(String[] args) {
        init();
        TestVectorConcurrent tvc = new TestVectorConcurrent();
        TestVectorConcurrent.T1 tv1 = tvc.new T1();
        Thread t1 = new Thread(tv1);
        TestVectorConcurrent.T2 tv2 = tvc.new T2();
        Thread t2 = new Thread(tv2);
        t1.start();
        t2.start();
    }

    private void retrieve() {
        synchronized (obj) {
            for (String s : v) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                }
                System.out.println(s);
            }
        }
    }

    private void remove() {
        synchronized (obj) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
            }
            v.remove(10);
        }
    }

    class T1 implements Runnable {
        @Override
        public void run() {
            retrieve();
        }
    }

    class T2 implements Runnable {
        @Override
        public void run() {
            remove();
        }
    }
}
package com.karl.test;

import java.util.List;
import java.util.Vector;

public class TestVectorConcurrent {

    public static List<String> v = new Vector<String>();

    private static void init() {
        for (int i = 1; i <= 20; i++) {
            v.add("helloworld:" + i);
        }
    }

    public static void main(String[] args) {
        init();
        TestVectorConcurrent tvc = new TestVectorConcurrent();
        TestVectorConcurrent.T1 tv1 = tvc.new T1();
        Thread t1 = new Thread(tv1);
        TestVectorConcurrent.T2 tv2 = tvc.new T2();
        Thread t2 = new Thread(tv2);
        t1.start();
        t2.start();
    }

    private void retrieve() {
        for (String s : v) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
            }
            System.out.println(s);
        }

    }

    private void remove() {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
        }
        v.remove(10);

    }

    class T1 implements Runnable {
        @Override
        public void run() {
            retrieve();
        }
    }

    class T2 implements Runnable {
        @Override
        public void run() {
            remove();
        }
    }

原文地址:https://www.cnblogs.com/zhonghan/p/2721547.html