12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- package J20250730.demo13;
- import java.util.Collections;
- import java.util.HashSet;
- import java.util.Set;
- /**
- * @author WanJl
- * @version 1.0
- * @title Demo01
- * @description
- * 题目 1:多线程操作 HashSet 的线程安全问题
- * 需求:
- * 创建 3 个线程,同时向一个 HashSet 中添加 1-100 的整数(每个线程负责不同区间,
- * 如线程 1 加 1-33,线程 2 加 34-66,线程 3 加 67-100),观察最终集合大小是否为 100
- * (可能出现重复添加),然后使用 Collections.synchronizedSet () 包装 HashSet,
- * 确保线程安全并验证结果。
- * @create 2025/7/30
- */
- public class Demo01 {
- public static void main(String[] args) throws InterruptedException {
- Set<Integer> set=new HashSet<>();
- Set<Integer> synchronizedSet = Collections.synchronizedSet(new HashSet<>());
- testSet(set,"线程不安全的集合");
- testSet(synchronizedSet,"线程安全的集合");
- }
- private static void testSet(Set<Integer> set,String label) throws InterruptedException {
- Thread t1=new Thread(()->{
- for (int i = 1; i <=33 ; i++) {
- set.add(i);
- }
- System.out.println(label+Thread.currentThread().getName()+"最终大小:"+set.size());
- },"线程1");
- Thread t2=new Thread(()->{
- for (int i = 34; i <=66 ; i++) {
- set.add(i);
- }
- System.out.println(label+Thread.currentThread().getName()+"最终大小:"+set.size());
- },"线程2");
- Thread t3=new Thread(()->{
- for (int i = 67; i <=100 ; i++) {
- set.add(i);
- }
- System.out.println(label+Thread.currentThread().getName()+"最终大小:"+set.size());
- },"线程3");
- t1.start();
- t2.start();
- t3.start();
- t1.join();
- t2.join();
- t3.join();
- System.out.println(label+"最终大小:"+set.size());
- }
- }
|