Java集合框架中的并发修改问题示例

原创 ╰+哭是因爲堅強的太久メ 2024-10-07 21:15 140阅读 0赞

在Java的集合框架中,并发修改(Concurrent Modification, CMS)是一个常见的性能问题。当一个线程同时添加和删除元素时,就可能发生CMS问题。

以下是一个简单的示例,演示了如何在List中并发修改:

  1. import java.util.ArrayList;
  2. import java.util.List;
  3. public class ConcurrentModificationExample {
  4. private List<Integer> list = new ArrayList<>();
  5. // 添加元素的线程
  6. public void addThread() {
  7. new Thread(() -> {
  8. for (int i = 0; i < 10000; i++) {
  9. list.add(i); // 并发添加元素
  10. }
  11. })).start();
  12. }
  13. // 删除元素的线程
  14. public void removeThread() {
  15. new Thread(() -> {
  16. for (int i = 9999; i >= 0; i--) { // 反向遍历
  17. list.remove(i); // 并发删除元素
  18. }
  19. })).start();
  20. }
  21. public void testConcurrentModification() throws InterruptedException {
  22. System.out.println("Starting threads...");
  23. addThread(); // 添加元素的线程
  24. removeThread(); // 删除元素的线程
  25. System.out.println("Waiting for threads to finish...");
  26. Thread.sleep(1000); // 等待线程执行完毕
  27. System.out.println("Checking list contents after threads finished...");
  28. if (list.equals(new ArrayList<>())) // 列表内容为空
  29. System.out.println("List contents are empty after concurrent modification.");
  30. else {
  31. System.out.println("List contents do not match expected after concurrent modification.");
  32. }
  33. }
  34. public static void main(String[] args) throws InterruptedException {
  35. ConcurrentModificationExample example = new ConcurrentModificationExample();
  36. example.testConcurrentModification(); // 运行测试
  37. }
  38. }

在这个例子中,两个线程分别在添加元素和删除元素。由于并发修改了列表,导致结果不符合预期。

这就是Java集合框架中并发修改问题的一个简单示例。在实际使用中,需要遵循相关的最佳实践来避免这类问题。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,140人围观)

还没有评论,来说两句吧...

相关阅读