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] 
    
  • 相关阅读:
    day10 Java学习(开发工具.Eclipse)
    day9 Java学习(面向对象Package关键字)
    day8 Java学习(面向对象.多态&接口)
    day7 Java学习(面向对象.继承)
    day5 Java学习(面向对象)
    day4 Java学习(数组)
    day3 Java学习(循环结构)
    day2 Java学习(位运算符)
    2019-05-26 java学习日记
    2019-05-25 java学习日记
  • 原文地址:https://www.cnblogs.com/JuncaiF/p/11373963.html
Copyright © 2011-2022 走看看