注意:使用Vecor集合类的时候,需要注意一个问题。当使用Vecor进行迭代器操作的时候,如果其它线程正在执行add()或者remove()等操作的时候,
很有可能出现ConcurrentModificationException异常。这样会导致迭代器遍历的时候报错,导致无法遍历,严重影响程序的功能。
今天特意模拟了一下这个异常,和解决了这个问题。写下这篇博客,希望大家使用Vector的时候注意这个问题和怎么解决!希望可以对大家带来帮助,可能写的不怎么好,希望大家指出!
import java.util.Iterator; import java.util.Vector; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; /** * Vector ConcurrentModificationException 异常模拟, 和解决 * Created by wang.honglin on 2018/8/1. */ public class VectorTest { /** * Vector ConcurrentModificationException 异常模拟 */ static class ExceptionTest { public static void main(String[] args) { Vector vector = new Vector(10); new Thread(() -> { // 在使用迭代器iterator()或者listIterator()的时候,只有当前迭代器可以add()和remove()。 // 如果其它线程并发操作该数组元素,那么iterator.next()会快速抛出ConcurrentModificationException Iterator iterator = vector.listIterator(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } while (iterator.hasNext()) { System.out.println(iterator.next()); } }).start(); new Thread(() -> { vector.add(3); }).start(); } } /** * 解决Vector ConcurrentModificationException 问题 * 当需要使用迭代器的时候,添加锁,遍历完成后,再释放锁 */ static class MeasuresTest{ public static void main(String[] args) { Vector vector = new Vector(10); vector.add("1"); vector.add("2"); vector.add("3"); ReentrantLock reentrantLock = new ReentrantLock(); new Thread(() -> { try { // 尝试获取锁,设置一个获取锁超时时间 if (reentrantLock.tryLock(2000, TimeUnit.SECONDS)) { Iterator iterator = vector.listIterator(); Thread.sleep(1000); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } catch (InterruptedException e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } }).start(); new Thread(() -> { try { // 尝试获取锁,设置一个获取锁超时时间 if (reentrantLock.tryLock(2000, TimeUnit.SECONDS)) { vector.add(3); } } catch (InterruptedException e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } }).start(); } } }