目前比较常用的构建线程安全的List有三种方法:
- 使用Vector容器
- 使用Collections的静态方法synchronizedList(List< T> list)
- 采用CopyOnWriteArrayList容器
Vector
Vector类实现了可扩展的对象数组,并且它是线程安全的。它和ArrayList在常用方法的实现上很相似,不同的只是它使用了同步关键词synchronized修饰方法。
Vector中的add方法:
public void add(int index, E element) {
insertElementAt(element, index);
}
...
// 使用了synchronized关键词修饰
public synchronized void insertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index

最低0.47元/天 解锁文章
162

被折叠的 条评论
为什么被折叠?



