单例模式场景模拟和问题解决

饿汉式单例

java 复制代码
private static Student student = new Student();

不存在线程安全问题

懒汉式单例

线程安全问题

java 复制代码
package org.example.Singleton;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class SingletonTest {
    private static Student student = new Student();

    private static Car car = null;

    private static AtomicInteger count = new AtomicInteger(0);

    private static ExecutorService threadPoolExecutor = Executors.newCachedThreadPool();

    private static final CountDownLatch latch = new CountDownLatch(15);

    SingletonTest() throws InterruptedException {
        threadNonSafeLoad();
    }

    public static void main(String[] args) throws InterruptedException {
        loadInstance();
        latch.await();
        System.out.println(count.get());
    }

    private static void threadSafeLoad() {

    }

    private void threadNonSafeLoad() {
        //        System.out.println(this.car);
        if (this.car == null) {
            count.addAndGet(1);
            this.car = new Car();
        }
        latch.countDown();
    }

    private static void loadInstance() {
        for (int i = 0; i < 15; i++) {
//            Thread.sleep(50);
            Thread thread = new Thread(() -> {
                try {
                    new SingletonTest();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            threadPoolExecutor.execute(thread);
        }
    }
}

class Student {
    private String name;
}

class Car {
    private String name;
}

运行结果:

java 复制代码
会多次创建`Car`对象
1~15

解决方法-双重判断

java 复制代码
    private void threadSafeLoad() {
        if (this.car == null) {
            // 避免每次都加锁进行判断
            synchronized (SingletonTest.class) {
                if (this.car == null) {
                    count.addAndGet(1);
                    this.car = new Car();
                }
            }
        }
        latch.countDown();
    }
java 复制代码
    SingletonTest() throws InterruptedException {
//        threadNonSafeLoad();
        threadSafeLoad();
    }

运行结果:

java 复制代码
1
相关推荐
Yue丶越21 小时前
【C语言】深入理解指针(二)
c语言·开发语言·数据结构·算法·排序算法
m0_7482480221 小时前
C++中的位运算符:与、或、异或详解
java·c++·算法
介一安全21 小时前
从 0 到 1 玩转 2025 最新 WebGoat 靶场:环境搭建 + 全关卡漏洞解析(超级详细)
java·web安全·网络安全·靶场
web安全工具库21 小时前
Linux进程的:深入理解子进程回收与僵尸进程
java·linux·数据库
沐浴露z21 小时前
详解【限流算法】:令牌桶、漏桶、计算器算法及Java实现
java·算法·限流算法
兜有米啦21 小时前
python练习题3
开发语言·python
chxii1 天前
Spring Boot 响应给客户端的常见返回类型
java·spring boot·后端
Wzx1980121 天前
go基础语法练习
开发语言·后端·golang
老友@1 天前
一次由 PageHelper 分页污染引发的 Bug 排查实录
java·数据库·bug·mybatis·pagehelper·分页污染
AI分享猿1 天前
小白学规则编写:雷池 WAF 配置教程,用 Nginx 护住 WordPress 博客
java·网络·nginx