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

饿汉式单例

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
相关推荐
ChrisitineTX几秒前
凌晨突发Java并发问题:synchronized锁升级导致接口超时,排查过程全记录
java·数据库·oracle
还没想好取啥名3 分钟前
C++11新特性(一)——原始字面量
开发语言·c++
谷粒.8 分钟前
测试数据管理难题的7种破解方案
运维·开发语言·网络·人工智能·python
zzhongcy10 分钟前
Java: HashMap 和 ConcurrentHashMap的区别
java·开发语言
✎ ﹏梦醒͜ღ҉繁华落℘40 分钟前
菜鸟的算法基础
java·数据结构·算法
梨落秋霜40 分钟前
Python入门篇【基础语法】
开发语言·python
老华带你飞1 小时前
社团管理|基于Java社团管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
shayudiandian1 小时前
用LangChain打造你自己的智能问答系统
java·数据库·langchain
啊森要自信1 小时前
【STM32】USART串口通信
c语言·开发语言·stm32·单片机·嵌入式硬件
小白学大数据1 小时前
Python 多线程爬取社交媒体品牌反馈数据
开发语言·python·媒体