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

饿汉式单例

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
相关推荐
冬奇Lab几秒前
【Kotlin系列10】协程原理与实战(上):结构化并发让异步编程不再是噩梦
android·开发语言·kotlin
薛不痒3 分钟前
项目:矿物分类(训练模型)
开发语言·人工智能·python·学习·算法·机器学习·分类
jason.zeng@15022074 分钟前
spring boot mqtt开发-原生 Paho 手动封装(最高灵活性,完全自定义)
java·spring boot·后端
姜太小白5 分钟前
【前端】JavaScript字符串执行方法总结
开发语言·前端·javascript
被星1砸昏头5 分钟前
C++与Node.js集成
开发语言·c++·算法
xixi09246 分钟前
selenium的安装配置
开发语言·python
sunnyday04268 分钟前
Filter、Interceptor、Spring AOP 的执行顺序详解
java·spring boot·后端·spring
程序员zgh10 分钟前
C++ 纯虚函数 — 抽象接口
c语言·开发语言·c++·经验分享·笔记·接口隔离原则
想用offer打牌16 分钟前
一站式了解Spring AI Alibaba的Memory机制
java·人工智能·后端·spring·chatgpt·系统架构