Collections

发布时间 2023-10-30 15:51:32作者: anpeiyong

 

ArrayList相关

Collections.synchronizedList(new ArrayList<>())

public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
        
    }

  

public class Collections {

        static class SynchronizedCollection<E> implements Collection<E>, Serializable {
            final Collection<E> c;  // Backing Collection
            final Object mutex;     // Object on which to synchronize

            SynchronizedCollection(Collection<E> c) {
                this.c = Objects.requireNonNull(c);
                mutex = this;
            }

            public boolean add(E e) {
                synchronized (mutex) {return c.add(e);}
            }
            public boolean remove(Object o) {
                synchronized (mutex) {return c.remove(o);}
            }
        }

        static class SynchronizedList<E> extends SynchronizedCollection<E> implements List<E> {
            final List<E> list;

            SynchronizedList(List<E> list) {
                super(list);
                this.list = list;
            }
        }
        
        static class SynchronizedRandomAccessList<E> extends SynchronizedList<E> implements RandomAccess {
            SynchronizedRandomAccessList(List<E> list) {
                super(list);
            }
        }
    }