码迷,mamicode.com
首页 > 编程语言 > 详细

java并发之CopyOnWriteArraySet

时间:2019-08-18 21:44:30      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:stack   str   static   inner   iter   vat   int   over   ack   

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

标签:stack   str   static   inner   iter   vat   int   over   ack   

原文地址:https://www.cnblogs.com/JuncaiF/p/11373963.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!