gpt4 book ai didi

java - 如何通过测试证明 arraylist 不是线程安全的?

转载 作者:搜寻专家 更新时间:2023-10-31 19:33:43 25 4
gpt4 key购买 nike

在我们的应用程序中,我们在 ArrayList.add(Object o) 操作中遇到了 ArrayIndexOutOfBounds 异常。最明显的解释是线程安全,但我无法重新创建事件。我试过创建两个线程。在一个中我添加元素,在另一个中我删除它们(或清除数组),但我第二次没有得到异常。我的意思是很明显它可以通过查看 ArrayList 的源代码来实现,但是能够演示它会很好。

我已经运行这个测试很长一段时间了,没有任何异常:

public class Test {
static ArrayList a = new ArrayList();

public static void main(String[] args) throws Exception {
Thread t1 = new Thread() {
public void run() {
while (true) {
if (a.size() > 0)
a.remove(0);
}
}
};

Thread t2 = new Thread() {
public void run() {
while (true) {
a.add(new Object());
}
}
};

t2.start();
Thread.sleep(100);
t1.start();
}
}

最佳答案

感谢 isnot2bad 的评论,我发现我的假设存在问题。问题在于并发添加,而不是添加/删除。我能够创建一个失败的测试:

static ArrayList a = new ArrayList(1);

public static void main(String[] args) throws Exception {
Thread t1 = new Thread() {
public void run() {
while (true) {
a.add(new Object());
}
}
};

Thread t2 = new Thread() {
public void run() {
while (true) {
a = new ArrayList(1);
a.add(new Object());
a.add(new Object());
}
}
};

t2.start();
Thread.sleep(100);
t1.start();
}

在第一个线程的添加行中,我得到了这个:

Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 2 

:)

关于java - 如何通过测试证明 arraylist 不是线程安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18983362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com