public class DateUtilTest {
    public void testDeleteElement(List<String> list) throws Exception{
        for (int i=list.size()-1;i>=0;i--) {
            if(list.get(i).equals("5")){
                list.remove(i);
                continue;
            }

            if(i%1000 == 0){
                Thread.sleep(100);
                System.out.println("Current Thread is " + Thread.currentThread().getName());
            }
        }

        System.out.println(list.toString());
    }

    public void testDeleteElementWithIterator(List<String> list) throws Exception{
        Iterator<String> iterator = list.iterator();
        int i=0;
        while(iterator.hasNext()){
            if(iterator.next().equals("5")){
                iterator.remove();
            }
            if(i%1000 == 0){
                Thread.sleep(100);
                System.out.println("Current Thread is " + Thread.currentThread().getName());
            }
            i++;
        }

        System.out.println(list.toString());
    }

    public static void main(String[] args) throws Exception{
        DateUtilTest test = new DateUtilTest();
        List<String> list = test.init();

        Thread t1 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try{
                            test.testDeleteElementWithIterator(list);
                            System.out.println("Thread1 is running");
                        }catch(Throwable t){
                            t.printStackTrace();
                        }

                    }
                }, "thread-1"
        );

        Thread t2 = new Thread(
                new Runnable() {
                    @Override
                    public void run() {
                        try{
                            test.testDeleteElementWithIterator(list);
                            System.out.println("Thread2 is running");
                        }catch(Throwable t){
                            t.printStackTrace();
                        }
                    }
                }, "thread-2"
        );

        t1.start();
        t2.start();
    }

    public List<String> init(){
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        list.add("5");
        list.add("6");
        list.add("7");
        list.add("8");
        list.add("9");

        for(int i=10; i< 100000; i++){
            list.add(i + "");
        }

        return list;
    }
}



用iterator会报ConcurrentModificationException异常在并发的时候,用index不会。