线程同步容器(用Collections..synchronized同步的(gold_axe)

老马说编程

ArrayList -> Vector, Stack
HashMap -> HashTable (key‘ value不能为null)
Collections.synchronizedXXX(List, Set, Map)
List list = Collections.synchronizedList(Lists.newArrayList());

里面每个用synchronized同步

性能较低,不如 专为并发设计的容器类
CopyOnWriteArrayList

ConcurrentHashMap

ConcurrentLinkedQueue

ConcurrentSkipListSet

但是这样一边改,循环还是不行,会有ConcurrentModificationException
循环也要加锁
入参是:
final List list = Collections .synchronizedList(new ArrayList<>());

private static void startIteratorThread(final List list) {
    Thread iteratorThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                //锁住 不让其他线程改list
                synchronized(list){
                    for (String str : list) {
                    }    
                }//synchronized 结束
            }
        }
    });
    iteratorThread.start();
}

你可能感兴趣的:(线程同步容器(用Collections..synchronized同步的(gold_axe))