标签:stack str static inner iter vat int over ack
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]
标签:stack str static inner iter vat int over ack
原文地址:https://www.cnblogs.com/JuncaiF/p/11373963.html