JAVA线程安全的懒汉式 单例模式

JAVA使用同步机制将单例模式中的懒汉式改写为线程安全的

JAVA设计模式是日常开发中用的比较多的,这里就举例说明一种使用同步机制将单例模式中的懒汉式改写为线程安全的,据说面试经常会被考到,大家可以保存下来哦!废话不多说,直接上代码:
首先得创建单例模式类,将它们的属性跟构造器都设置成私有的:

class Singleton {
	private static Singleton instance = null;
	private Singleton() {
   System.out.println("需要用到的代码块");
}
{
   System.out.println("这里需要用到的代码块不一定要放到构造器中,也可以直接放到代码块里面");
}
}

然后设置getInstance()方法,去操作这个类

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

看起来有点繁琐,其实很简单;首先判断属性是否为空,如果为空,则去实例化它的对象,如果不为空,这返回它的属性,即已经实例化好的对象,达到单例模式的效果。使用synchronized()方法的意思是,只允许一个线程对其进行实例化,实现线程安全。
如何使用这种模式呢,很简单,直接调用它的getInstance()方法就行了

    public static void main(String[] args) {
        Singleton.getInstance();
    }

完整代码:

public class SingletonTest {

    public static void main(String[] args) {
        Singleton.getInstance();
    }

}

class Singleton {

    private static Singleton instance = null;

    private Singleton() {

        System.out.println("需要用到的代码块");
    }
        {
        System.out.println("这里需要用到的代码块不一定要放到构造器中,也可以直接放到代码块里面");
    }
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

这种模式的设计思想是只能实例化一个对象且只能实例化一次,外部只能去使用,不能对其进行修改等操作,在开发中还是比较常用的。
最后附上运行结果截图:
在这里插入图片描述


版权声明:本文为qq_43230149原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。