• 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方法直接按照索引查询数组即可。

    返回顶部

  • 相关阅读:
    linux 磁盘管理学习笔记
    Apache的Order Allow Deny心得
    NodeJs 笔记
    JavaScript 笔记
    MySQL 学习笔记
    HTML 转义符
    UTF-8 BOM(EF BB BF)
    [ Python
    [ Python
    [ Python
  • 原文地址:https://www.cnblogs.com/yanhui007/p/12587686.html
Copyright © 2020-2023  润新知