1 List
代码语言:javascript复制package com.shi.list;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* ArrayList再线程安全不安全方面的问题
* @author shiye
* 1 new ArrayList<>();
* 结果:抛出大量的异常
* java.util.ConcurrentModificationException
at java.util.ArrayList.forEach(Unknown Source)
at com.shi.list.TestArrayList1.lambda$0(TestArrayList1.java:20)
at java.lang.Thread.run(Unknown Source)
2 原因:add()方法没有加锁
3 解决方案
3.1 使用 new Vector<>() ,安全问题可以解决 但是并发性问题无法得到保障
3.2 使用 Collections.synchronizedList(new ArrayList<>());
3.3 使用 new CopyOnWriteArrayList(); 写的时候复制一份 再去操作
*/
public class TestArrayList1 {
public static void main(String[] args) {
//1 new ArrayList<>();
//2 new Vector<>();
//3 Collections.synchronizedList(new ArrayList<>());
List<String> list = new CopyOnWriteArrayList();
for (int i = 0; i < 30; i ) {
new Thread( () -> {
list.add((String) UUID.randomUUID().toString().subSequence(0, 5));
System.out.println(list);
System.out.println();
}).start();
}
}
}
2 Set
代码语言:javascript复制package com.shi.list;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Set的线程不安全问题
* @author shiye
*
* 如果直接使用 HashSet
* 会导致 Exception in thread "Thread-26" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(Unknown Source)
*/
public class TestArraySet1 {
public static void main(String[] args) {
Set<String> set = new CopyOnWriteArraySet(); //Collections.synchronizedSet(new HashSet()); //new HashSet<>();
for (int i = 0; i < 30; i ) {
new Thread( () -> {
set.add((String) UUID.randomUUID().toString().subSequence(0, 5));
System.out.println(set);
System.out.println();
}).start();
}
}
}
3 Map
代码语言:javascript复制package com.shi.list;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Map 中的线程不安全问题
* @author shiye
*
* 使用 HashMap 出现的问题
* {0=abf8f, 1=6d6e8, 2=945c7, 3=bd78e, 4=76208}
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(Unknown Source)
{0=a0f65, 1=dab37, 2=15df6}
解决方案:
1 Collections.synchronizedMap(new HashMap<>());
2 使用 new ConcurrentHashMap(); //java.util.concurrent.ConcurrentHashMap
*
*/
public class TestMap {
public static void main(String[] args) {
Map<String,Object> map = new ConcurrentHashMap();//Collections.synchronizedMap(new HashMap<>());//new HashMap<>();
for (int i = 0; i < 30; i ) {
new Thread( () -> {
for (int j = 0; j < 100; j ) {
map.put(j "" ,(String) UUID.randomUUID().toString().subSequence(0, 5));
}
System.out.println(map);
System.out.println();
}).start();
}
}
}