concurrent-集合

CopyOnWriteArrayList
ConcurrentHashMap
ArrayBlockingQueue

CopyOnWriteArrayList

public class CopyOnWriteArrayList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    //用来保证同时只能有一个线程修改list
    final transient ReentrantLock lock = new ReentrantLock();

    private transient volatile Object[] array;
}
    public static void main(String[] args) {
        CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList(new ArrayList());
        copyOnWriteArrayList.add("123");
        copyOnWriteArrayList.get(2);
    }

构造器有两种:无参和有参

    public CopyOnWriteArrayList() {
        setArray(new Object[0]);
    }
    final void setArray(Object[] a) {
        array = a;
    }
     //参数为Collection类型
    public CopyOnWriteArrayList(Collection<? extends E> c) {
        Object[] elements;
        if (c.getClass() == CopyOnWriteArrayList.class)
            elements = ((CopyOnWriteArrayList<?>)c).getArray();
        else {
            elements = c.toArray();
            // c.toArray might (incorrectly) not return Object[] (see 6260652)
            if (elements.getClass() != Object[].class)
                elements = Arrays.copyOf(elements, elements.length, Object[].class);
        }
        setArray(elements);
    }

添加方法:

 public boolean add(E e) {
        final ReentrantLock lock = this.lock;
        lock.lock();//加锁
        try {
            Object[] elements = getArray();
            int len = elements.length;
            //赋值一份新的数组,大小为原数组大小加1
            Object[] newElements = Arrays.copyOf(elements, len + 1);
            //将添加的元素添加到新数组上
            newElements[len] = e;
            setArray(newElements);
            return true;
        } finally {
            lock.unlock();
        }
    }

get方法直接按照索引查询数组即可。

返回顶部

posted @ 2020-03-28 15:41  平淡454  阅读(113)  评论(0编辑  收藏  举报