您好,欢迎来到一二三四网。
搜索
您的当前位置:首页设计模式之单例模式(懒汉式)

设计模式之单例模式(懒汉式)

来源:一二三四网

使用volatile的特性(保证可见性),实现单例模式

package com.dada.thread.threaddemo.chapter03;

/**
 * @author: dada
 * @date: 2020/12/17
 * @description: 单例模式
 */
public class SingleDemo {

    private static volatile SingleDemo instance = null;

    private SingleDemo(){
        System.out.println(Thread.currentThread().getName() + "\t 单例");
    }

    public static SingleDemo getInstance(){
        if (instance == null) {
            synchronized (SingleDemo.class){
                if (instance == null){
                    instance = new SingleDemo();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            new Thread(() ->{
                System.out.println(SingleDemo.getInstance() == SingleDemo.getInstance());
            } ).start();
        }

    }

}

输出:

Thread-0	 单例
true
true
true
true
true
true
true
true
true
true

Process finished with exit code 0

 

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- howto1234.net 版权所有 湘ICP备2023021910号-3

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务