zoukankan      html  css  js  c++  java
  • java并发之CopyOnWriteArraySet

    java并发之CopyOnWriteArraySet

    CopyOnWriteArraySet是基于CopyOnWriteArrayList实现的,持有CopyOnWriteArrayList的内部对象,它的迭代器也是CopyOnWriteArrayList的迭代器,add操作通过addAllAbsent或者addIfAbsent去重。

    例子

    package javalearn.javabase.concurrent;
    
    import lombok.extern.slf4j.Slf4j;
    
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    @Slf4j
    public class CopyOnWriteArraySetTest {
        private static CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();
    
        private static int capcity = 5;
    
        //private static HashSet<String> set =new HashSet<>();
        public static void main(String[] args) {
            CopyOnWriteArraySetTest.InnerThread t1 = new InnerThread();
            CopyOnWriteArraySetTest.InnerThread t2 = new InnerThread();
            t1.start();
            t2.start();
            try {
                Thread.sleep(1000);
                log.info("collection:{} ",set.toString());
    
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
    
        }
    
        static class InnerThread extends Thread {
            @Override
            public void run() {
                for (int i = 0; i < capcity; i++) {
                    set.add(String.valueOf(i));
                    set.add(String.valueOf(i));
                    iterator(set);
                }
            }
        }
    
        public static void iterator(Set set) {
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                iterator.next();
            }
    
        }
    }
    
    

    结果

    21:10:09.967 [main] INFO javalearn.javabase.concurrent.CopyOnWriteArraySetTest - collection:[0, 1, 2, 3, 4] 
    
  • 相关阅读:
    交互题
    线段树
    最小生成树
    拓扑排序
    欧拉回路
    RMQ问题
    dfs序与求子树子节点(染了色)的个数
    dp题
    树状数组与离散化
    没做完的题
  • 原文地址:https://www.cnblogs.com/JuncaiF/p/11373963.html
Copyright © 2011-2022 走看看