章
目
录
本文主要讲解Java并发编程:集合的线程安全问题演示与解决相关内容,我们来一起学习下吧!
List集合线程不安全
为了演示 List集合线程不安全的问题,我们创建10个线程对同一个List集合进行修改:
public class ThreadDemo4 {
public static void main(String[] args) {
//创建ArrayList集合
List<String> list = new ArrayList<>();
//创建线程对list进行修改
for(int i = 0; i < 10; i++) {
new Thread(()->{
//往集合中添加元素
list.add(UUID.randomUUID().toString().substring(0, 8));
//获取集合中的元素
System.out.println(list);
}, String.valueOf(i)).start();
}
}
}
运动代码发现直接报错:ConcurrentModificationException,类似如下:
错误原因:访问的同时又在进行修改。
解决方案1:Vector
将arrayList替换为Vector
//创建集合
List<String> list = new Vector<>();
然后再去试下就不报错了,这是为什么?因为Vector中的方法都加了synchronized
关键字,例如add方法:
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}
也就是说ArrayList中方法是线程不安全的,而Vector中方法是线程安全的。
解决方案2:Collection.synchronizedList()
利用Collections的静态方法synchronizedList
:
List<String> list = Collections.synchronizedList(new ArrayList());
解决方案3 :CopyOnWriteArrayList
写时复制技术:当有元素要往列表中添加元素时,会先复制一份原列表,添加好元素后,将原引用指向新的列表。
因为是复制一份进行写操作的,所以同时有其他线程要读时,依然可以对原数组进行读操作。缺点就是:可能读的不是最新的元素。
我们看下add方法源码:
public boolean add(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
Object[] elements = getArray();
int len = elements.length;
Object[] newElements = Arrays.copyOf(elements, len + 1);
newElements[len] = e;
setArray(newElements);
return true;
} finally {
lock.unlock();
}
}
可见其实是使用了ReentrantLock 可重入锁进行实现线程安全的。既照顾了并发读,也实现了独立写。适合读多写少的应用场景。
HashSet集合线程不安全
HashSet集合本身也是线程不安全的,这里我们演示10个线程对同一个hashSet进行读写操作。
public class TestTread {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
for(int i = 0; i < 10; i++) {
new Thread(()->{
set.add(UUID.randomUUID().toString().substring(0, 8));
System.out.println(set);
}, "thread"+i).start();
}
}
}
同ArrayList一样,报错了,如果你测试不报错,那就加大线程数量效果更明显:
解决方案:可以使用CopyOnWriteArraySet()或Collections.synchronizedSet()来解决
HashMap线程不安全
同样地,HashMap也是线程不安全的,代码演示:
public class ThreadDemo6 {
public static void main(String[] args) {
Map<String, Integer> hashMap = new HashMap<>();
for(int i = 0; i < 10; i++) {
int finalI = i;
new Thread(()->{
hashMap.put(UUID.randomUUID().toString().substring(0, 8), finalI);
System.out.println(hashMap);
}).start();
}
}
}
解决方案就是使用ConcurrentHashMap()或者Collections.synchronizedMap()来实现线程安全。
总结
以上就是Java并发编程:集合的线程安全问题演示与解决相关内容,希望对你有帮助,欢迎持续关注潘子夜个人博客,学习愉快哦!