多线程之集合类
CopyOnWriteArrayList
ConcurrentHashMap
CopyOnWriteArraySet
public class SynCollectionTest {
//1.同步list: 每个线程都添加一个元素,看总数
private CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); //线程安全
//private List<String> list = new ArrayList<String>(); //线程不安全、会报错
public static void main(String[] args) {
SynCollectionTest o = new SynCollectionTest();
for(int i=0;i<100;i++) {
o.new ListThread().start();
}
}
class ListThread extends Thread{
public void run() {
list.add("str");
System.out.println(list.size());
}
}
}
public class SynMapTest {
private ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>(); //线程安全,键、值不能为空值
//private Hashtable<String, Integer> map = new Hashtable<String, Integer>(); //线程不安全
//private HashMap<String, Integer> map = new HashMap<String, Integer>(); //线程不安全,抛出异常
public static void main(String[] args) {
SynMapTest o = new SynMapTest();
for(int n=0;n<1000;n++) {
o.map.put("s"+n, new Integer(0));
}
//并发删除,抛出异常 java.util.ConcurrentModificationException
for(int i=0;i<10;i++) {
o.new MapThread().start();
}
}
class MapThread extends Thread{
public void run() {
Set<String> keys = map.keySet();
for(String k : keys) {
map.remove(k);
}
}
}
}
public class SynSet {
private CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<String>(); //线程安全
//private Set<String> set = new HashSet<String>(); //线程不安全,抛出异常java.util.ConcurrentModificationException
private Random r = new Random();
public static void main(String[] args) {
SynSet o = new SynSet();
for(int i=0;i<1000;i++) {
o.set.add(String.valueOf(o.r.nextInt(1000)));
}
for(int i=0;i<10000;i++) {
o.new SetThread().start();
}
}
class SetThread extends Thread{
public void run() {
Iterator<String> keys = set.iterator();
String k = null;
while(keys.hasNext()) {
k = keys.next();
set.remove(k);
}
}
}
}
上一篇: lodop打印控件
下一篇: 动态代理设计模式 Java