java并发之CopyOnWriteArraySet

Posted juncaif

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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] 

以上是关于java并发之CopyOnWriteArraySet的主要内容,如果未能解决你的问题,请参考以下文章

Java并发编程:并发容器之ConcurrentHashMap

Java并发编程:并发容器之ConcurrentHashMap(转载)

Java并发编程:并发容器之ConcurrentHashMap

Java并发编程:并发容器之CopyOnWriteArrayList

Java并发--并发容器之ConcurrentHashMap

java并发之CopyOnWriteArraySet