Java集合框架中的并发修改问题示例
在Java的集合框架中,并发修改(Concurrent Modification, CMS)是一个常见的性能问题。当一个线程同时添加和删除元素时,就可能发生CMS问题。
以下是一个简单的示例,演示了如何在List中并发修改:
import java.util.ArrayList;
import java.util.List;
public class ConcurrentModificationExample {
private List<Integer> list = new ArrayList<>();
// 添加元素的线程
public void addThread() {
new Thread(() -> {
for (int i = 0; i < 10000; i++) {
list.add(i); // 并发添加元素
}
})).start();
}
// 删除元素的线程
public void removeThread() {
new Thread(() -> {
for (int i = 9999; i >= 0; i--) { // 反向遍历
list.remove(i); // 并发删除元素
}
})).start();
}
public void testConcurrentModification() throws InterruptedException {
System.out.println("Starting threads...");
addThread(); // 添加元素的线程
removeThread(); // 删除元素的线程
System.out.println("Waiting for threads to finish...");
Thread.sleep(1000); // 等待线程执行完毕
System.out.println("Checking list contents after threads finished...");
if (list.equals(new ArrayList<>())) // 列表内容为空
System.out.println("List contents are empty after concurrent modification.");
else {
System.out.println("List contents do not match expected after concurrent modification.");
}
}
public static void main(String[] args) throws InterruptedException {
ConcurrentModificationExample example = new ConcurrentModificationExample();
example.testConcurrentModification(); // 运行测试
}
}
在这个例子中,两个线程分别在添加元素和删除元素。由于并发修改了列表,导致结果不符合预期。
这就是Java集合框架中并发修改问题的一个简单示例。在实际使用中,需要遵循相关的最佳实践来避免这类问题。
还没有评论,来说两句吧...