1、写加锁,保证不会写混乱 2、写在一个Copy副本上,而不是原始数据上 3、读写分离,保证最终一致性 4、多个操作不能保证原子性

示例1

由于ArrayList、LinkedList、Vector是线程不安全的,当并发遍历操作的时候会抛出ConcurrentModificationException

部分ArrayList实现的迭代器部分代码

  1. private class Itr implements Iterator<E> {
  2. public E next() {
  3. //检查是否存在并发操作
  4. checkForComodification();
  5. int i = cursor;
  6. if (i >= size)
  7. throw new NoSuchElementException();
  8. Object[] elementData = ArrayList.this.elementData;
  9. if (i >= elementData.length)
  10. throw new ConcurrentModificationException();
  11. cursor = i + 1;
  12. return (E) elementData[lastRet = i];
  13. }
  14. final void checkForComodification() {
  15. //
  16. if (modCount != expectedModCount)
  17. throw new ConcurrentModificationException();
  18. }
  19. }
  1. package collection;
  2. import java.util.ArrayList;
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import java.util.Vector;
  6. import java.util.concurrent.CopyOnWriteArrayList;
  7. /**
  8. * {@link CopyOnWriteArrayList}
  9. *
  10. * @author lihongjian
  11. * @since 2021/2/27
  12. */
  13. public class CopyOnWriteArrayListDemo {
  14. public static void main(String[] args) {
  15. // List<Integer> list = new ArrayList<>();
  16. // Vector list = new Vector();
  17. // List<Integer> list = new LinkedList<>();
  18. CopyOnWriteArrayList list = new CopyOnWriteArrayList<>();
  19. for (int i = 0; i < 10000; i++) {
  20. list.add(i);
  21. }
  22. T1 t1 = new T1(list);
  23. T2 t2 = new T2(list);
  24. t1.start();
  25. t2.start();
  26. }
  27. public static class T1 extends Thread {
  28. List<Integer> list ;
  29. public T1(List<Integer> list){
  30. this.list = list;
  31. }
  32. @Override
  33. public void run() {
  34. for (Integer integer : list) {
  35. }
  36. }
  37. }
  38. public static class T2 extends Thread {
  39. List<Integer> list ;
  40. public T2(List<Integer> list){
  41. this.list = list;
  42. }
  43. @Override
  44. public void run() {
  45. for(int i = 0; i < list.size(); i++){
  46. list.remove(i);
  47. }
  48. }
  49. }
  50. }

CopyOnWriteArrayList源码

  1. public E remove(int index) {
  2. //先加锁
  3. final ReentrantLock lock = this.lock;
  4. lock.lock();
  5. try {
  6. //把原数组取出来
  7. Object[] elements = getArray();
  8. int len = elements.length;
  9. E oldValue = get(elements, index);
  10. int numMoved = len - index - 1;
  11. if (numMoved == 0)
  12. //如果删除的是末尾的元素,则拷贝前len-1个元素到新的副本上,再切换引用
  13. setArray(Arrays.copyOf(elements, len - 1));
  14. else {
  15. //否则将其他元素拷贝到新的副本上,并切换引用
  16. //复制到新的副本上,保证其他线程的读操作还是读的旧副本
  17. Object[] newElements = new Object[len - 1];
  18. System.arraycopy(elements, 0, newElements, 0, index);
  19. System.arraycopy(elements, index + 1, newElements, index,
  20. numMoved);
  21. setArray(newElements);
  22. }
  23. return oldValue;
  24. } finally {
  25. lock.unlock();
  26. }
  27. }
  28. add方法类似,也是拷贝新的副本出来进行操作

示例2-多个步骤不能保证原子性

package collection;

import com.sun.imageio.plugins.wbmp.WBMPImageReader;

import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @author lihongjian
 * @since 2021/2/27
 */
public class CopyOnWriteArrayListDemo2 {

    private final static CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList();

    public static void main(String[] args) {
        /*
         *这个例子证明,多个步骤的操作,不能保证原子性
         * list.size()获取到的数,再使用的时候,可能list的长度已经变了
         */
        test();
    }

    public static void test() {

        for (int i = 0; i < 10000; i++) {
            list.add(i);
        }

        new Thread(() -> {
            while (true) {
                if (list.size() > 0) {
                    list.get(list.size() - 1); //下一个操作时,可能size已经变了
                } else {
                    break;
                }
            }
        }).start();

        new Thread(() -> {
            while (true) {
                if (list.size() <= 0) {
                    break;
                }
                list.remove(0);
            }
        }).start();
    }
}