Demo01.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package J20250730.demo13;
  2. import java.util.Collections;
  3. import java.util.HashSet;
  4. import java.util.Set;
  5. /**
  6. * @author WanJl
  7. * @version 1.0
  8. * @title Demo01
  9. * @description
  10. * 题目 1:多线程操作 HashSet 的线程安全问题
  11. * 需求:
  12. * 创建 3 个线程,同时向一个 HashSet 中添加 1-100 的整数(每个线程负责不同区间,
  13. * 如线程 1 加 1-33,线程 2 加 34-66,线程 3 加 67-100),观察最终集合大小是否为 100
  14. * (可能出现重复添加),然后使用 Collections.synchronizedSet () 包装 HashSet,
  15. * 确保线程安全并验证结果。
  16. * @create 2025/7/30
  17. */
  18. public class Demo01 {
  19. public static void main(String[] args) throws InterruptedException {
  20. Set<Integer> set=new HashSet<>();
  21. Set<Integer> synchronizedSet = Collections.synchronizedSet(new HashSet<>());
  22. testSet(set,"线程不安全的集合");
  23. testSet(synchronizedSet,"线程安全的集合");
  24. }
  25. private static void testSet(Set<Integer> set,String label) throws InterruptedException {
  26. Thread t1=new Thread(()->{
  27. for (int i = 1; i <=33 ; i++) {
  28. set.add(i);
  29. }
  30. System.out.println(label+Thread.currentThread().getName()+"最终大小:"+set.size());
  31. },"线程1");
  32. Thread t2=new Thread(()->{
  33. for (int i = 34; i <=66 ; i++) {
  34. set.add(i);
  35. }
  36. System.out.println(label+Thread.currentThread().getName()+"最终大小:"+set.size());
  37. },"线程2");
  38. Thread t3=new Thread(()->{
  39. for (int i = 67; i <=100 ; i++) {
  40. set.add(i);
  41. }
  42. System.out.println(label+Thread.currentThread().getName()+"最终大小:"+set.size());
  43. },"线程3");
  44. t1.start();
  45. t2.start();
  46. t3.start();
  47. t1.join();
  48. t2.join();
  49. t3.join();
  50. System.out.println(label+"最终大小:"+set.size());
  51. }
  52. }