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

饿汉式单例

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
相关推荐
tealcwu13 小时前
【Unity基础】为什么游戏需要物理按键映射?从 Unity Input Manager 到跨引擎输入设计
java·游戏·unity
vipxieliang13 小时前
Spring Boot 性能优化实战:从启动加速到运行时调优
java·spring boot
AI全栈学习助手13 小时前
告别“转圈等待”:Spring Boot + SSE 让大模型像 ChatGPT 一样流式输出
java·人工智能·spring boot·后端·aigc
天天被压力13 小时前
【A股分钟级高频数据完全手册 #02】Python调用股票1分钟数据接口:Pro版最新分时取数与字段解析
java·人工智能·python
代码不停13 小时前
Spring Aop
java·数据库·spring
时间的拾荒人14 小时前
CMake 实战指南:从基础语法到静态库/动态库制作与链接
开发语言·c++·面试
道尔柯南14 小时前
C++ STL 入门详解:从认识标准模板库到掌握学习方法
java·c++·学习方法
杨凯凡14 小时前
Spring Boot 4 升级为什么卡在 Jackson 3?包名、配置与兼容迁移指南
java·spring boot 4·技术升级·jackson 3·spring framework
天天被压力14 小时前
【A股分钟级高频数据完全手册 #01】Pro版接口体系总览与REST鉴权:42篇地图与从0接入
java·人工智能·python
xyouyuweizhu14 小时前
Java InetAddress 详解:从 IP 地址表示到主机名解析
java·开发语言·python