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);
}
}
- 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());