1、ArrayList线程不安全;CopyOnWriteArrayList线程安全
package concurrent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Auth: zhouhongliang
* Date:2019/8/1
* CopyOnWriteArrayList 替代 ArrayList
*/
public class CopyOnWriteArrayListDemo {
public static void main(String[] args) {
List<Integer> list = new CopyOnWriteArrayList<>();
//List<Integer> list = new CopyOnWriteArrayList<>();
for (int i=0;i<1000;i++){
list.add(i);
}
Iterator iterator = list.iterator();
while(iterator.hasNext()){
list.remove(iterator.next());
}
System.out.println(list);
}
}
2、HashMap线程不安全;HashTable synchronize线程安全、```
ConcurrentHashMap采用”分段锁”线程安全;
package concurrent;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
- Auth: zhouhongliang
- Date:2019/8/1
*/
public class ConcurrentHashMapDemo {
public static void main(String[] args) throws InterruptedException {
Map map = new HashMap();//线程不安全
//Map map = new Hashtable();//线程安全
//Map map = new ConcurrentHashMap();//线程安全
ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch countDownLatch = new CountDownLatch(10000);
for (int i=0;i<10000;i++){
final Integer index = i;
executorService.execute(()->{
map.put(index,index);
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println(map.size());
}
}