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

饿汉式单例

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
相关推荐
biubiubiu0706几秒前
RocketMQ Dashboard安装
java·rocketmq·java-rocketmq
hai405872 分钟前
C#进阶:轻量级ORM框架Dapper详解
开发语言·microsoft·c#
野老杂谈9 分钟前
2.3 Python 基本运算符
开发语言·python·python基础·编程入门·运算符·算术运算·逻辑运算
Stringzhua31 分钟前
Java哈希算法
java·开发语言·哈希算法
gma99937 分钟前
C++ 重要特性探究
开发语言·c++
zhyjhacker39 分钟前
C++ primer plus 第17 章 输入、输出和文件:文件输入和输出03:文件模式:二进制文件
开发语言·c++·cocoa
一叶祇秋40 分钟前
Leetcode - 136双周赛
java·算法·leetcode
下海的alpha1 小时前
理解Spring框架2:容器IOC
java·spring·rpc
柯3491 小时前
JVM内存结构
java·jvm
神奇夜光杯1 小时前
Python酷库之旅-第三方库Pandas(069)
开发语言·人工智能·python·excel·pandas·标准库及第三方库·学习与成长