我正在研究线程并在这里发现了这个片段:
我们创建并启动两个相同的 java.lang.Thread
并让它们连续修改一个 ArrayList
而不做任何关于这是非线程安全的事情,因为我们'我只是在做一个研究。
两个线程都只是同一个类 NoteThread
的实例。在 run()
方法中有两个操作:
add(item)
到列表从列表中删除(0)
。
这两个操作在 1000 次迭代中执行。
public class Solution {
public static void main(String[] args) {
new NoteThread().start();
new NoteThread().start();
}
public static class Note {
public static final List<String> notes = new ArrayList<String>();
public static void addNote(String note) {
notes.add(0, note);
}
public static void removeNote(String threadName) {
String note = notes.remove(0);
if (note == null) {
System.out.println("Another thread has already deleted the note");
} else if (!note.startsWith(threadName)) {
System.out.println("Thread [" + threadName + "] has deleted [" + note + "]");
}
}
}
public static class NoteThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
Note.addNote(getName() + "-Note" + i);
Note.removeNote(getName());
}
}
}
}
有时,它会在列表为空时抛出 IndexOutOfBoundsException: Index: 0, Size: -1
而我不明白这是怎么可能的。
输出示例:
Thread [Thread-1] has deleted [Thread-0-Note597] Another thread has already deleted the note Thread [Thread-0] has deleted [Thread-1-Note558] Another thread has already deleted the note Thread [Thread-1] has deleted [Thread-0-Note635] Another thread has already deleted the note Thread [Thread-0] has deleted [Thread-1-Note580]
我们可以 100% 确定,在同一个线程中,项目的创建总是发生在删除之前,所以我假设不可能遇到线程想要删除项目但找不到的情况一。
更新:Sergey Rybalkin已经非常清楚地解释了程序化执行顺序的概念(我最初没有在问题中提到但无论如何都是这个意思)而且最重要的是,他已经回答了这个问题:
If
Thread 1
adds something,Thread 2
will not see the changes in some situations.
在 Java 内部,我们修改的每个对象实际上在使用它的每个线程中都有它的缓存副本。因为这个例子没有做任何关于线程安全的事情,我们修改的数组也被缓存到每个线程。现在,既然如此,就有可能:
注意,这只是我的理解,我不是专家
线程 1
将数组复制到它的缓存中。线程 2
将数组复制到它的缓存中。线程 1
将一个项目添加到它的缓存数组中。线程 2
将一个项目添加到它的缓存数组中。线程 1
从其缓存数组中删除一个项目。线程 1
将其缓存数组刷新到实际数组中。JVM
传播更改并将实际数组上传到该对象的所有用户 - 到Thread 2
。因此,第二个线程现在拥有当前为空的数组的更新版本。线程 2
从其缓存数组中删除一个项目。- 异常:列表已经为空:
IndexOutOfBoundsException:索引:0,
大小:-1
<
最佳答案
您正在并发修改数据结构 ArrayList
- ArrayList 不是线程安全的。
- 您的循环迭代不是原子的。
- 您不提供任何订购元素。
如果我们命名 A1
- 添加线程 1,A2
- 添加线程 2,R1
- 删除 int 线程 1,R2
- 在线程 2 和之前的 >
中删除。
在一次迭代中,您可以获得:
A1 > R1 > A2 > R2
A1 > A2 > R1 > R2
A1 > A2 > R2 > R1
- ...
我们只知道总是A1 > R1
和A2 > R2
此外,调度程序可以在线程 1 中执行多次迭代,并且仅在切换到线程 2 之后执行。
因此,没有理由期望您的两个线程中的任何操作顺序。在这种情况下,您所拥有的只是在单个线程中添加和删除的编程顺序。但是您没有 Happens Before 关系。查看更多 JLS 17 . 但最好先有一个基本的了解。
关于java - 为什么异步线程不能同时修改 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44326983/