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

饿汉式单例

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
相关推荐
workflower1 小时前
时序数据获取事件
开发语言·人工智能·python·深度学习·机器学习·结对编程
CoderYanger2 小时前
C.滑动窗口-求子数组个数-越长越合法——2799. 统计完全子数组的数目
java·c语言·开发语言·数据结构·算法·leetcode·职场和发展
C++业余爱好者2 小时前
Java 提供了8种基本数据类型及封装类型介绍
java·开发语言·python
想用offer打牌2 小时前
RocketMQ如何防止消息丢失?
java·后端·架构·开源·rocketmq
林杜雨都2 小时前
Action和Func
开发语言·c#
皮卡龙2 小时前
Java常用的JSON
java·开发语言·spring boot·json
火山灿火山2 小时前
Qt常用控件(三)
开发语言·qt
利刃大大3 小时前
【JavaSE】十三、枚举类Enum && Lambda表达式 && 列表排序常见写法
java·开发语言·枚举·lambda·排序
float_六七3 小时前
Java反射:万能遥控器拆解编程
java·开发语言
han_hanker3 小时前
java 异常类——详解
java·开发语言