• java并发之CopyOnWirteArrayList


    java并发之CopyOnWirteArrayList

    CopyOnWirteArrayList的实现

    它用了ReentrantLock保证了add,set,remove操作的安全,同时使用volatile定义内部数组保证了可见性,
    之所以叫CopyOnWrite就是因为很多方法都是通过Array.copy或者System.arraycopy,操作中有数组的
    拷贝,所以写的操作效率很低

    例子

    package javalearn.javabase.concurrent;
    
    import lombok.extern.slf4j.Slf4j;
    
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.concurrent.CopyOnWriteArrayList;
    
    @Slf4j
    
    public class CopyWriteOnArrayListTest {
    
        private static int capcity = 5;
        private static List<String> list = new CopyOnWriteArrayList<String>();
        //private static List<String> list = new ArrayList<>();会抛出异常ConcurrentModificationException
        public static void main(String[] args) {
            InnerThread t1 = new InnerThread();
            InnerThread t2 =new InnerThread();
            t1.start();
            t2.start();
    
        }
    
        static class InnerThread extends Thread {
            @Override
            public void run() {
                for (int i = 0; i < capcity; i++) {
                    list.add(String.valueOf(i));
                    iteratorList(list);
                }
            }
        }
        public static void iteratorList(List list){
            Iterator iterator =list.iterator();
            while(iterator.hasNext()){
                iterator.next();
            }
    
        }
    }
    
    
  • 相关阅读:
    [POI2005]A Journey to Mars 单调队列
    滑动窗口 单调队列
    逆序对 模拟贪心
    迷宫 dfs爆搜
    [Usaco2019 Feb]The Great Revegetation
    [Usaco2007 Dec]挑剔的美食家
    [HNOI2004]宠物收养所
    bzoj2639 矩形计算
    [Ahoi2013]作业
    Gty的二逼妹子序列
  • 原文地址:https://www.cnblogs.com/JuncaiF/p/11373964.html
Copyright © 2020-2023  润新知