@Test
public void testMThread() throws InterruptedException {
int count = 3500;
CountDownLatch countDownLatch = new CountDownLatch(count);
List<Integer> arrayList = new LinkedList<>();
Runnable listOperations = () -> {
// arrayList.addAll(Arrays.asList(1, 2, 3, 4, 5, 6));
arrayList.add(1);
countDownLatch.countDown();
};
for (int i = 0; i < count; i++) {
new Thread(listOperations).start();
}
countDownLatch.await();
int size = arrayList.size();
System.out.println(size);
}
预期结果是3500,实际输出:
添加元素方法代码
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #addLast}.
*
* @param e element to be appended to this list
* @return {@code true} (as specified by {@link Collection#add})
*/
public boolean add(E e) {
linkLast(e);
return true;
}
/**
* Links e as last element.
*/
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
LinkedList 使用链表数据结构存储元素,所以在其成员变量中有三个属性:
transient int size = 0;
/**
* Pointer to first node.
*/
transient Node<E> first;
/**
* Pointer to last node.
*/
transient Node<E> last;
分别为集合大小、链表第一个元素、链表最后一个元素,在方法linkLast中,如果链表为空,则当前元素为第一个元素,否则将将元素添加到链表尾部。
在LinkedList实现中,添加元素是没有扩容代码的,那么线程不安全的原因应该就在这个 linkLast 方法中操作的成员变量以及Node对象本身。
首先方法内部、成员变量、Node对象本身
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
都没有任何同步或者锁措施,那么也就容易出现线程并发修改时出现问题,比如同时修改一个Node元素的尾部,只有一个成功,就会出现丢链,同时修改size属性,就会出现实际链表元素数量比记录的size值大的情况。